springboot实现数据库数据导出生成Excel报表
一.导入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 就会弹出保存文件地址。
bug怎么这么多!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战