1、在pom.xml中添加Excel的相关依赖包
<!-- Excel--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
2、在Controller里写入相关数据
@ResponseBody @RequestMapping("/carnjExport") //将列表数据导出为Excel public void carnjExport(HttpServletResponse response){ try{ //设置Excel表格信息 XSSFWorkbook workbook=new XSSFWorkbook(); XSSFSheet sheet=workbook.createSheet(); //创建表头 XSSFRow row=sheet.createRow(0); //数据库相关信息 row.createCell(0).setCellValue("编号"); row.createCell(1).setCellValue("车牌号"); row.createCell(2).setCellValue("年检时间"); row.createCell(3).setCellValue("下次年检时间"); row.createCell(4).setCellValue("送年检人"); row.createCell(5).setCellValue("年检地点"); row.createCell(6).setCellValue("年检状态"); row.createCell(7).setCellValue("添加人"); row.createCell(8).setCellValue("添加时间"); //数据填充 //获取列表数据 List<Carnj> carnjList=carnjService.showAllCarnj(); int rowindex=1; for(Carnj carnj:carnjList){ XSSFRow row1= sheet.createRow(rowindex++); row1.createCell(0).setCellValue(carnj.getBh()); row1.createCell(1).setCellValue(carnj.getCarid()); row1.createCell(2).setCellValue(carnj.getNjsj()); row1.createCell(3).setCellValue(carnj.getXcnjsj()); row1.createCell(4).setCellValue(carnj.getSnjr()); row1.createCell(5).setCellValue(carnj.getNjdd()); row1.createCell(6).setCellValue(carnj.getNjzt()); row1.createCell(7).setCellValue(carnj.getTjr()); row1.createCell(8).setCellValue(carnj.getTjsj()); } //设置响应头信息 response.setContentType("application/vnd.ms-excel"); response.setHeader("content-Disposition","attachment;filename=carnj.xlsx"); //将Excel文档写入到响应中 ServletOutputStream outputStream= response.getOutputStream(); workbook.write(outputStream); outputStream.flush(); outputStream.close(); }catch (Exception e){ e.printStackTrace(); } }
3、在显示列表里给出超链接
<div id="top"> <span><a href="/showsaveCarnj">年检登记</a>|<a href="/carnjExport">导出Excel</a></span> </div>
4、实现效果
单击导出实现以下页面: