HTML页面导出Excel表格
注:页面不要用ajax跳转controller,因为ajax不会弹出下载页面。
一、引入依赖,放入pom.xml文件中
<!-- 以下导出Excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
二、从页面获取查询数据库的条件
arr 数组是查询条件
注:如果你是查询数据库的所有数据就不用传参了
//跳转controller
location.href="exportExcel?arr="+arr;
三、controller层
//导出Excel
@RequestMapping("exportExcel")
public void exportExcel(int[] arr, HttpServletResponse response){
List<Registration> list=new ArrayList<Registration>();
for (int i=0;i<arr.length;i++){
//从数据库查询导出的数据并放入集合中
list.add(registrationService.getRegistrationByreId(arr[i]));
}
//新建一个Excel 对象
//把weorkbook对象 理解为一个 excel
Workbook workbook=new XSSFWorkbook();
//在excel中创建一个 sheet 并将sheet文件命名为“挂号信息”
Sheet sheet=workbook.createSheet("挂号信息");
//定义一个字符串数组,用于Excel表头数据
String[] titles={"病历号","姓名","证件类型","证件号"};
//创建一行
Row row=sheet.createRow(0);
//循环字符串数组
for (int i = 0; i <titles.length ; i++) {
//cell 创建一个单元格
Cell cell=row.createCell(i);
//往第一行的单元格里面放字符串数组中的数据
cell.setCellValue(titles[i]);
}
//根据上面的步骤把数据库查出来的数据都放入单元格中
for (int i = 0; i <list.size() ; i++) {
//创建一行,因为表头占了一行,所以从i+1开始
row=sheet.createRow(i+1);
//把list中的对象一个一个取出来
Registration registration=list.get(i);
//创建单元格
Cell reIdCell=row.createCell(0);
//把数据放入单元格
reIdCell.setCellValue(registration.getReId());
//同上
Cell reNameCell=row.createCell(1);
reNameCell.setCellValue(registration.getReName());
Cell reTypeCell=row.createCell(2);
reTypeCell.setCellValue(registration.getReType());
Cell reTypenoCell=row.createCell(3);
reTypenoCell.setCellValue(registration.getReTypeno());
}
try {
//设置表名
String fileName= URLEncoder.encode("病历表.xlsx","UTF-8");
//下面是固定格式不用动
response.setContentType("application/octet-stream");
response.setHeader("content-disposition","attachment;filename="+fileName);
response.setHeader("filename",fileName);
//把workbook对象 写出去,到 response的输出流
workbook.write(response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
}