springboot导出excel多个sheet导出的实现
作者:Carver0808
在Java开发过程中,合理配置pom.xml文件对项目的管理和构建至关重要,通过添加依赖管理项目所需的库,简化了项目构建过程,同时,掌握导出excel工具类的使用,可以有效地处理数据导出需求,提高工作效率,本文结合个人经验
springboot导出excel多个sheet导出
1.pom.xml
<!--文件导出--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency>
2、controller
@GetMapping("/export") public void export(HttpServletResponse response) { //创建模拟数据 List<User> dataList = new ArrayList<>(); for (int i = 1; i <= 20; i++) { User user = new User(i,"张三" + i, 23, "男", 173); dataList.add(user); } //导出 ExcelExportUtil.exportExcel(response, dataList,"用户信息.xls",9L); }
3、导出excel工具类
import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.URLEncoder; import java.util.List; public class ExcelExportUtil { /** * 导出excel 多个sheet * @param response 响应流 * @param dataList 导出数据 * @param fileName 文件名 * @param sheetSize 每个sheet容量 */ public static void exportExcel(HttpServletResponse response, List<User> dataList, String fileName, Long sheetSize) { //创建HSSFWorkbook对象(excel的文档对象) HSSFWorkbook workbook = new HSSFWorkbook(); try (ServletOutputStream out = response.getOutputStream()) { //计算要分几个sheet int sheetNum = dataList.size() / sheetSize.intValue(); if (dataList.size() % sheetSize.intValue() != 0) { sheetNum += 1; } //依次对每个sheet页面进行操作 for (int i = 0; i < sheetNum; i++) { int num = 1; HSSFSheet sheet = workbook.createSheet("sheet" + (i+1)); HSSFRow row = sheet.createRow(0); //创建单元格并设置单元格内容 row.createCell(0).setCellValue("学号"); row.createCell(1).setCellValue("姓名"); row.createCell(2).setCellValue("年龄"); row.createCell(3).setCellValue("性别"); row.createCell(4).setCellValue("身高"); //i * sheetSize.intValue() 记录上次取值得位置 for (int j = i * sheetSize.intValue(); j < dataList.size(); j++) { User user = dataList.get(j); //每个页面把取够sheetSize条数据即可 if(num < sheetSize + 1){ HSSFRow row1 = sheet.createRow(num); row1.createCell(0).setCellValue(user.getNo()); row1.createCell(1).setCellValue(user.getName()); row1.createCell(2).setCellValue(user.getAge()); row1.createCell(3).setCellValue(user.getSex()); row1.createCell(4).setCellValue(user.getHeight()); }else{break;} num++; } } response.setContentType("application/msexcel;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); workbook.write(out); } catch (IOException e) { e.printStackTrace(); } } }
4、测试结果
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。