- 在pom.xml中添加导出excel的依赖。
<!-- 导出excel的依赖 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14-beta1</version>
</dependency>
- 在jsp页面添加“导出excel”的超链接
<a href="${pageContext.request.contextPath }/download">导出EXCEL</a>
- 在控制层编写接收“导出excel”请求的方法。
@RequestMapping("/download")
public void download(HttpServletResponse response) throws Exception {
List<Employee> emList=empoloyeeService.getAllEmployee();
@SuppressWarnings("resource")
Workbook workbook=new XSSFWorkbook();
Sheet sheet = workbook.createSheet("登录日志");
CellStyle titleStyle = workbook.createCellStyle();
titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
XSSFFont font = (XSSFFont) workbook.createFont();
font.setFontName("仿宋_GB2312");
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
font.setFontHeightInPoints((short) 12);
titleStyle.setFont(font);
String[] titles ={"员工编号","员工姓名","职位","入职日期","薪水","奖金","所在部门"};
Row row = sheet.createRow(0);
for (int i =0;i<titles.length;i++){
Cell cell=row.createCell(i);
cell.setCellValue(titles[i]);
sheet.setColumnWidth(i, (int)(titles[i].getBytes().length * 1.2d * 256 > 12 * 256 ? titles[i].getBytes().length * 1.2d * 256 : 12 * 256));
cell.setCellStyle(titleStyle);
}
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle.setWrapText(true);
for (int i = 0;i<emList.size();i++){
row=sheet.createRow(i+1);
Employee mid=emList.get(i);
Cell empnoCell =row.createCell(0);
empnoCell.setCellValue(mid.getEmpno());
Cell enameCell =row.createCell(1);
enameCell.setCellValue(mid.getEname());
Cell jobCell =row.createCell(2);
jobCell.setCellValue(mid.getJob());
Cell hiredateCell =row.createCell(3);
hiredateCell.setCellValue(mid.getHiredate());
Cell salCell =row.createCell(4);
salCell.setCellValue(mid.getSal());
Cell commCell =row.createCell(5);
commCell.setCellValue(mid.getComm());
Cell dnameCell =row.createCell(6);
dnameCell.setCellValue(mid.getDepartment().getDname());
row.getCell(0).setCellStyle(cellStyle);
row.getCell(1).setCellStyle(cellStyle);
row.getCell(2).setCellStyle(cellStyle);
row.getCell(3).setCellStyle(cellStyle);
row.getCell(4).setCellStyle(cellStyle);
row.getCell(5).setCellStyle(cellStyle);
row.getCell(6).setCellStyle(cellStyle);
}
String fileName= URLEncoder.encode("员工信息.xlsx","UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition","attachment;filename="+fileName);
response.setHeader("filename",fileName);
workbook.write(response.getOutputStream());
}
- 测试。测试结果如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200518160602871.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzkyMDc3OA==,size_16,color_FFFFFF,t_70)