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();
}
}
}
不错,知识共享,让更多人避免踩坑