写入excel代码优化
上一篇代码不够通用,所以优化了下代码
*传入数据为了保证传值和取值的一致性,可以使用linkedhashmap*
public class UpdateExcelUtil {
public static void updateExcelUtil(File file,List<Map> mapList) throws Exception {
FileInputStream fileInputStream = new FileInputStream(file);
XSSFWorkbook sheets = new XSSFWorkbook(fileInputStream);
XSSFSheet sheet = sheets.getSheetAt(0);
//获取最后一行
int lastRowNum = sheet.getLastRowNum();
//删除数据
if(lastRowNum>1){
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
sheet.removeRow(row);
}}
for (int rowId = 0; rowId < mapList.size(); rowId++) {
Map<String, String> map = mapList.get(rowId);
XSSFRow newRow = sheet.createRow(rowId + 1);
int cellnum = 0;
for (Map.Entry<String, String> entrySet : map.entrySet()) {
String value = entrySet.getValue();
XSSFCell cell = newRow.createCell(cellnum);
cell.setCellValue(value);
cellnum++;
}
}
FileOutputStream fileOutputStream = new FileOutputStream(file);
sheets.write(fileOutputStream);
fileInputStream.close();
fileOutputStream.close();
}