Devil_566 2016-09-30 08:33 采纳率: 0%
浏览 7075

java利用POI写入Excel表中关于时间格式的问题。已解决,供参考

public static void writeExcel(String fileDir,String sheetName, List> dataList){

createExcel(fileDir, sheetName, dataList);
//创建workbook

File file = new File(fileDir);

HSSFWorkbook workbook = null;
try {

workbook = new HSSFWorkbook(new FileInputStream(file));

} catch(IOException e) {

e.printStackTrace();

}

//流

FileOutputStream out = null;

HSSFSheet sheet = workbook.getSheet(sheetName);

// 获取表格的总行数

int rowCount = sheet.getLastRowNum() + 1; // 需要加一

// 获取表头的列数

int columnCount = sheet.getRow(0).getLastCellNum();
//日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
HSSFCellStyle dateCellStyle=workbook.createCellStyle();
short df=workbook.createDataFormat().getFormat("yyyy-mm-dd");
dateCellStyle.setDataFormat(df);
try {

Row row = null;

// 获得表头行对象

HSSFRow titleRow = sheet.getRow(0);

Date temp = null;
if(titleRow!=null){

for (int i = 0, len = dataList.size(); i < len; i++) {
row = sheet.createRow(rowCount+i);//最新要添加的一行

for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { // 遍历表头
String title = titleRow.getCell(columnIndex).toString().trim();
String data = dataList.get(i).get(title).toString();
Cell cell = row.createCell(columnIndex);
try{
temp = sdf.parse(data);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(temp);
cell.setCellStyle(dateCellStyle);
sheet.setColumnWidth(columnIndex, 10 * 256);
} catch(Exception e){
cell.setCellValue(data);
}
}
}
}

out = new FileOutputStream(fileDir);

workbook.write(out);

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

  • 写回答

1条回答 默认 最新

  • RoidCoder 2016-09-30 11:25
    关注

    不错,知识共享,让更多人避免踩坑

    评论

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害