項目搭建
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爲模板文件,第一行第二行爲表頭