- pom文件安装以下jar包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
- 业务逻辑代码
public Workbook exportData() throws IOException {
List<CarInfo> seats = list();
Workbook wb = null;
wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("test");
Row r = sheet.createRow(0);
r.createCell(0).setCellValue("ID");
r.createCell(1).setCellValue("座位类型ID");
r.createCell(2).setCellValue("火车ID");
r.createCell(3).setCellValue("排数");
r.createCell(4).setCellValue("座位数");
r.createCell(5).setCellValue("卧铺间数");
r.createCell(6).setCellValue("床位数");
r.createCell(7).setCellValue("车厢号");
int count = 1;
for (CarInfo seat : seats) {
r = sheet.createRow(count++);
CreationHelper helper = wb.getCreationHelper();
XSSFHyperlink link = (XSSFHyperlink) helper.createHyperlink(HyperlinkType.FILE);
link.setAddress("apps/master-setting/"+seat.getId());
r.createCell(0).setCellValue(seat.getId());
r.createCell(0).setHyperlink(link);
r.createCell(1).setCellValue(seat.getSeatTypeId());
r.createCell(2).setCellValue(seat.getTrainId());
r.createCell(3).setCellValue(seat.getRowsNumber()!=null?seat.getRowsNumber():0);
r.createCell(4).setCellValue(seat.getSeatsNumber()!=null?seat.getSeatsNumber():0);
r.createCell(5).setCellValue(seat.getRoomsNumber()!=null?seat.getRoomsNumber():0);
r.createCell(6).setCellValue(seat.getBedsNumber()!=null?seat.getBedsNumber():0);
r.createCell(7).setCellValue(seat.getCarNo());
}
return wb;
}
- 控制器
@GetMapping(“downloadExcel”)
public void downloadExcel(HttpServletResponse response) throws IOException {
response.setContentType(“application/vnd.ms-excel;charset=utf-8”);
Workbook wb = service.exportData();
OutputStream os = response.getOutputStream();
response.setHeader(“Content-disposition”, “attachment;filename=” + sdf.format(new Date()) + “.xlsx”);// 默认Excel名称
wb.write(os);
os.close();
wb.close();
}