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个回答

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问