项目搭建
springboot >2.2.2.RELEASE
pom.xml导入POI
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.13</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.13</version>
</dependency>
代码
private void createWJWFile(List<Map<String, Object>> list, String path) throws IOException {
FileInputStream fileInputStream = null;
HSSFWorkbook workbook = null;
FileOutputStream fileOutputStream = null;
try {
//将模板复制到下载文件夹中并读取
String basePath = this.getClass().getResource("/").getPath().substring(1);
fileInputStream = new FileInputStream(basePath+"temp/demo.xls");
workbook = new HSSFWorkbook(fileInputStream);
//写入内容
//获取sheet
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFCell cellTitle = sheet.getRow(0).getCell(0);
String title = cellTitle.getStringCellValue();
cellTitle.setCellValue(format(title,"time", DateUtils.simpleDateFormatTime0.format(new Date())));
int i =1;
//第一二行为表头,数据从第三行开始
int rowIndex = 2;
for(Map<String,Object> map:wjwList){
HSSFRow tempRow = sheet.createRow(rowIndex);
//序号
tempRow.createCell(0).setCellValue(i+"");
tempRow.createCell(0).setCellValue(map.get("name").toString());
rowIndex++;
i++;
}
String fileName = path + "/demo.xls";
//将写入内容更新到excel
fileOutputStream = new FileOutputStream(fileName);
workbook.write(fileOutputStream);
fileOutputStream.flush();
}catch (Exception ex){
ex.printStackTrace();
}finally {
if(workbook!=null)
workbook.close();
if(fileInputStream!=null)
fileInputStream.close();
if(fileOutputStream!=null)
fileOutputStream.close();
}
}
- 参数list为导出数据
- 参数path为导出文件路径
- 项目根目录下temp/demo.xls为模板文件,第一行第二行为表头