首页 > 其他分享 >基于POI的Excel导出

基于POI的Excel导出

时间:2024-07-03 17:34:35浏览次数:1  
标签:sheet setCellStyle Excel 导出 createCell POI workbook setCellValue row

基于POI的Excel导出

1、后端依赖

 1 <dependencies>
 2     <dependency>
 3         <groupId>org.apache.poi</groupId>
 4         <artifactId>poi</artifactId>
 5         <version>5.2.3</version>
 6     </dependency>
 7     <dependency>
 8         <groupId>org.apache.poi</groupId>
 9         <artifactId>poi-ooxml</artifactId>
10         <version>5.2.3</version>
11     </dependency>
12 </dependencies>

2、前端

1  exportExcel(rows) {
2        window.location.href  = Environment.getReqDomain() + "/xxx/xxx/xxx/excelExport?param01=" + rows.param01 + '&param02=' + params02;
3  },

 

3、controller层

1
2 @GetMapping("/excelExport") 3 public void exportExcel(ExcelExportParams params, HttpServletResponse response) { 4 try { 5 corpBillService.exportExcel(params,response); 6 } catch (Exception e) { 7 LOGGER.error("接入单位对账excel导出失败 , ", e); 8 } 9 }

4、service层 

  1   @Override
  2     public void exportExcel(ExcelExportParams params, HttpServletResponse response) throws IOException {
  3         List<ExcelExportDto> list = xxxMapper.qryExcelExportByxxx(params.param01(), params.param02());
  4         
  5         String name = list.get(0)==null?"":list.get(0).getName();
  6         Integer totalNum = list.stream().mapToInt(ExcelExportDto::getSuccessNum).sum();
  7         // 创建工作簿
  8         Workbook workbook = new XSSFWorkbook();
  9         // 创建工作表
 10         Sheet sheet = workbook.createSheet("数据报表");
 11 
 12         // 设置默认行高和列宽行高20磅
 13         sheet.setDefaultRowHeightInPoints(20);
 14         for (int i = 0; i < 5; i++) {
 15             // 列宽14磅,256是因为单位转换
 16             sheet.setColumnWidth(i, 14 * 256);
 17         }
 18 
 19         // 设置表头样式
 20         CellStyle headerStyle = ExcelStyleUtil.createHeaderCellStyle(workbook);
 21         Row headerRow = sheet.createRow(0);
 22         String[] headers = {"月份", "单位名称", "业务系统","模板名称", "发送成功量"};
 23         for (int i = 0; i < headers.length; i++) {
 24             Cell cell = headerRow.createCell(i);
 25             cell.setCellStyle(headerStyle);
 26             cell.setCellValue(headers[i]);
 27         }
 28 
 29         // 填充数据并设置样式
 30         CellStyle dataCellStyle = ExcelStyleUtil.createDataCellStyle(workbook);
 31         for (int i = 0; i < list.size(); i++) {
 32             ExcelExportDto dto = list.get(i);
 33             Row row = sheet.createRow(i + 1);
 34             row.setHeightInPoints(20);
 35             // 月份
 36             row.createCell(0).setCellValue(dto.getMonth());
 37             // 单位名称
 38             row.createCell(1).setCellValue(dto.getCorpName());
 39             // 业务系统
 40             row.createCell(2).setCellValue(dto.getSystemName());
 41             // 模板名称
 42             row.createCell(3).setCellValue(dto.getTemplateName());
 43             // 发送成功量
 44             row.createCell(4).setCellValue(dto.getSendSuccessNum());
 45             // 设置每一格的数据样式
 46             for (int j = 0; j < 5; j++) {
 47                 row.getCell(j).setCellStyle(dataCellStyle);
 48             }
 49         }
 50 
 51         // 在末尾追加汇总行
 52         int lastRowNum = sheet.getLastRowNum();
 53         CellStyle sumCellStyle = ExcelStyleUtil.createSumCellStyle(workbook);
 54         Row sumRow = sheet.createRow(lastRowNum + 1);
 55 
 56 
 57         // 合并第二、三、四列
 58         CellRangeAddress mergedRegion = new CellRangeAddress(lastRowNum + 1, lastRowNum + 1, 1, 3);
 59         sheet.addMergedRegion(mergedRegion);
 60 
 61         // 填充汇总行的数据
 62         Cell cell = sumRow.createCell(0);
 63         cell.setCellValue("合计");
 64         cell.setCellStyle(sumCellStyle);
 65 
 66         // 为合并后的第二、三、四列添加数据
 67         Cell cell01 = sumRow.createCell(1);
 68         cell01.setCellValue("");
 69         cell01.setCellStyle(sumCellStyle);
 70         // 为合并后的第二、三、四列添加数据
 71         Cell cell02 = sumRow.createCell(2);
 72         cell02.setCellValue("");
 73         cell02.setCellStyle(sumCellStyle);
 74         // 为合并后的第二、三、四列添加数据
 75         Cell cell03 = sumRow.createCell(3);
 76         cell03.setCellValue("");
 77         cell03.setCellStyle(sumCellStyle);
 78         Cell cell04 = sumRow.createCell(4);
 79         cell04.setCellValue(totalNum);
 80         cell04.setCellStyle(sumCellStyle);
 81 
 82 
 83         // 创建输出流
 84         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
 85 
 86         // 写入工作簿到输出流
 87         try {
 88             workbook.write(outputStream);
 89         } catch (IOException e) {
 90             throw new RuntimeException(e);
 91         } finally {
 92             workbook.close();
 93         }
 94 
 95         // 设置响应头
 96         response.setContentType("application/vnd.ms-excel");
 97         response.setCharacterEncoding("utf-8");
 98         String fileName = "接入单位对账-" + System.currentTimeMillis() + ".xlsx";
 99         try {
100             response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
101         } catch (UnsupportedEncodingException e) {
102             throw new RuntimeException("导出数据报表失败", e);
103         }
104 
105         // 获取输出流中的字节数组
106         byte[] bytes = outputStream.toByteArray();
107 
108         // 将字节数组写入响应流
109         ServletOutputStream servletOutputStream = response.getOutputStream();
110         servletOutputStream.write(bytes);
111         servletOutputStream.flush();
112         servletOutputStream.close();
113     }

5、service层import依赖

1 import org.apache.poi.ss.usermodel.*;
2 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
3 
4 import java.io.FileOutputStream;
5 import java.io.IOException;

 

标签:sheet,setCellStyle,Excel,导出,createCell,POI,workbook,setCellValue,row
From: https://www.cnblogs.com/qi-Blog/p/18282191

相关文章

  • EasyExcel 填充+写入
    使用EasyExcel导出Excel时,有时会遇到如下情况:既要根据模板填充某些sheet又要根据业务写入某些sheetEasyExcel官方没有提供这样的示例,经过自己的研究和实验,得到了如下步骤:定义导出文件名StringfileName="测试.xlsx";获取模板文件InputStreamtemplateFile......
  • 记录一次使用easypoi时与源码博弈的过程
     最近刚刚接手了保险一线之声平台的开发和维护工作,第一个需要修复的问题是:平台的事件导出成excel功能在经过一次上线之后突然不可用了,于是就开始了几轮痛苦的排查以及与源码博弈的过程。 二、问题描述一线之声在事件查询菜单下支持将结果导出为Excel,程序中使用easypoi+......
  • 这份Excel+Python飞速搞定数据分析手册,简直可以让Excel飞起来
    微软在UserVoice上运营着⼀个反馈论坛,每个⼈都可以在这⾥提交新点⼦供他⼈投票。票数最⾼的功能请求是“将Python作为Excel的⼀门脚本语⾔”,其得票数差不多是第⼆名的两倍。尽管⾃2015年这个点⼦发布以来并没有什么实质性进展,但在2020年年末,Python之⽗GuidovanRoss......
  • 05-Excel初阶操作-学习笔记
    DATE函数函数格式:DATE(参数1,参数2,参数3)参数说明:参数1:年份;参数2:月份;参数3:日作用:将文本类型转换为正确的日期格式应用场景:身份证号提取出生日期其中,MID()是文本截取函数注意!如果输入2000-2-30使用date函数后会进行进位显示2000-3-1Year、Month、Day函数作用:日期拆分为......
  • PointCloudLib alpha shapes算法提取平面点云边界 C++版本
    测试效果算法简介AlphaShapes算法是一种用于提取平面点云边界特征的方法,以下是对其原理和步骤的详细解释:1.AlphaShapes算法概述目标:从点云数据中提取曲面边界信息,通过计算点云中点的Alpha形状,获得边界特征。Alpha形状:一个可以描述几何体边界的参数。其计算基于一......
  • excel基本操作:基础、数据条件格式、快捷键
    Excel有三个模式分别是选择模式、编辑模式和输入模式(有光标)=====》这些了解就够了,也是最基本的。1.快捷键:ctrl+shift+右三角   选择所有的直到右边没有空格的在体重的那个空格选择的时候,按住上面的组合键就会出现从体重那一列直到球员奖金那一列在按住ctrl+shift+下就......
  • python 输入文件夹路径,返回所有的层次结构 excel
    importosimportopenpyxlfromopenpyxl.stylesimportFontdefget_folder_structure(root_folder):folder_structure=[]forroot,dirs,filesinos.walk(root_folder):level=root.replace(root_folder,'').count(os.sep)indent=......
  • 解决办法:hyper-v导出虚拟机到ESXI报错找不到磁盘:dev disk by-uuid 4b85b6e9-f0d1-4dc
    linux救援模式可以进入系统,发现UUID都是正常的。执行以下命令确认的:[root@localhost~]#cat/etc/fstabUUID=4b85b6e9-f0d1-4dc8-a9dd-aafad7b4354c/xfsdefaults00UUID=24c8c603-e6bd-453c-982f-79e9df3468fd/bootxfsdefaults00UUID=53608cf9-17c1-40c5-85ed-f88......
  • 从PDF到OFD,国产化浪潮下多种文档格式导出的完美解决方案
    前言近年来,中国在信息技术领域持续追求自主创新和供应链安全,伴随信创上升为国家战略,一些行业也开始明确要求文件导出的格式必须为OFD格式。OFD格式目前在政府、金融、税务、教育、医疗等需要文件开放、共享和长期保存的行业中广泛应用。这种趋势在未来几年内将进一步增强。相......
  • 前端实现根据模版导出word【docxtemplater】
    场景有的时候我们需要根据后端提供的数据,然后结合word模版来生成word。我们可以使用第三方库docxtemplater效果依赖说明1、docxtemplater:这个插件可以通过预先写好的word,excel等文件模板生成对应带数据的文件2、pizzip:这个插件用来创建,读取或编辑.zip的文件(同步的,还有一个......