一.导入poi依赖
<!-- poi实现excel导入导出--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.15</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.15</version> </dependency>
主要用到该依赖下的两个类:XSSFWorkbook和HSSFWorkbook类。
XSSFWorkbook是Excel中的xlsx版本。
HSSFWorkbook是xls版本。
我使用的是xlsx版本的。
二.详细代码
业务层:
@Service public class GoodsServiceImpl implements GoodsService { @Autowired private GoodsMapper goodsMapper; @Override public XSSFWorkbook show() { List<Goods> list = goodsMapper.selectByExample(null);//查出数据库数据 XSSFWorkbook wb = new XSSFWorkbook(); Sheet sheet = wb.createSheet("Goods");//创建一张表 Row titleRow = sheet.createRow(0);//创建第一行,起始为0 titleRow.createCell(0).setCellValue("序号");//第一列 titleRow.createCell(1).setCellValue("名称"); titleRow.createCell(2).setCellValue("数量"); titleRow.createCell(3).setCellValue("库存"); int cell = 1; for (Goods goods : list) { Row row = sheet.createRow(cell);//从第二行开始保存数据 row.createCell(0).setCellValue(cell); row.createCell(1).setCellValue(goods.getGname());//将数据库的数据遍历出来 row.createCell(2).setCellValue(goods.getGprice()); row.createCell(3).setCellValue(goods.getTid()); cell++; } return wb; }
控制层:
@Controller public class GoodsController { @Autowired private GoodsService goodsService; @RequestMapping(value = "/export/goods",method = RequestMethod.GET) public void goodsExcel(HttpServletResponse response){ XSSFWorkbook wb =goodsService.show(); String fileName = "Goods报表.xlsx"; OutputStream outputStream =null; try { fileName = URLEncoder.encode(fileName,"UTF-8"); //设置ContentType请求信息格式 response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + fileName); outputStream = response.getOutputStream(); wb.write(outputStream); outputStream.flush(); outputStream.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
三.测试
运行项目,浏览器输入请求地址:/export/goods 就会弹出保存文件地址。