导入支持包
<!--POI 的支持jar-->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
代码
private final IBuildingService iBuildingService;
@Autowired
public TestPoiController(IBuildingService iBuildingService) {
this.iBuildingService = iBuildingService;
}
@GetMapping("/testPoi01")
public void testExecutePoi(HttpServletResponse httpServletResponse){
List<BuildingEntity> list = iBuildingService.list();
//1.在内存中创建一个excel文件
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
//2.创建工作簿
HSSFSheet sheet = hssfWorkbook.createSheet();
//3.创建标题行
HSSFRow titlerRow = sheet.createRow(0);
titlerRow.createCell(0).setCellValue("宿舍楼编号");
titlerRow.createCell(1).setCellValue("内含房间数");
titlerRow.createCell(2).setCellValue("宿舍楼层数");
titlerRow.createCell(3).setCellValue("应当住宿数");
//4.遍历数据,创建数据行
for (BuildingEntity BuildingEntity : list) {
//获取最后一行的行号
int lastRowNum = sheet.getLastRowNum();
HSSFRow dataRow = sheet.createRow(lastRowNum + 1);
dataRow.createCell(0).setCellValue(BuildingEntity.getBuildingNumber());
dataRow.createCell(1).setCellValue(BuildingEntity.getBuildingDormTotal());
dataRow.createCell(2).setCellValue(BuildingEntity.getBuildingFloorTotal());
dataRow.createCell(3).setCellValue(BuildingEntity.getBuildingShouldPeople());
}
//5.创建文件名
String fileName = "test1.xls";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileName);
hssfWorkbook.write(fos);
fos.flush();
fos.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
try {
httpServletResponse.setContentType("application/vnd.ms-excel");
httpServletResponse.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
OutputStream outputStream = httpServletResponse.getOutputStream();
hssfWorkbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}