今天给产品原型增加导出excel的功能,使用POI,方法如下:
1. 引用POI库(pom.xml)
org.apache.poipoi4.1.0org.apache.poipoi-ooxml4.1.0
2. 后端代码:
生成excel文件到指定目录,并返回文件名。
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; //... Listobjs ...; String[] colHeaders = new String[]{"编号", "名称", "部署日期"}; Workbook workbook = new HSSFWorkbook(); //使用xls格式 Sheet sheet = workbook.createSheet("sheet1"); Row headerRow = sheet.createRow(0); for(int i = 0; i < colHeaders.length; i++) { Cell cell = headerRow.createCell(i); cell.setCellValue(colHeaders[i]); } int rowNum = 1; for(Device obj: objs) { Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(obj.getNo()); row.createCell(1).setCellValue(obj.getName()); row.createCell(2).setCellValue(obj.getDeployTime()); } File folder = new File(exportPath); if(!folder.exists()) { folder.mkdir(); } String fileName = "XXX.xls"; String filePath = "D:\\"; try { FileOutputStream fileOut = new FileOutputStream(filePath + fileName); workbook.write(fileOut); fileOut.close(); workbook.close(); }catch(Exception e) { return "error: " + e.getMessage(); } return "ok" + fileName;
3. 前端调用下载:
//... window.open(url+"/file/download/export/" + fileName);
导出效果: