apache-poi导出excel数据

server/2025/2/11 8:58:19/

excel_1">excel导出

自动设置宽度,设置标题框,设置数据边框。

excel_5">excel导出

  1. 添加依赖
 <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.2</version></dependency>
  1. 编写工具类
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;/*** Excel导出**/
@Slf4j
public class MyExcelExportUtils {/*** 列的最大宽度*/private static final int COLUMN_MAX_WIDTH = 10240;/*** 列的最小宽度*/private static final int COLUMN_MIN_WIDTH = (int) (2048);/*** 导出Excel** @param excelExports excel集合* @param fileName     文件名* @param response     响应对象* @throws IOException*/public static void exportExcel(List<ExcelExport> excelExports, String fileName, HttpServletResponse response)throws IOException {
//        ServletOutputStream servletOutputStream = null;try {
//            servletOutputStream = response.getOutputStream();response.setContentType("multipart/form-data");response.setCharacterEncoding("utf-8");if (null == fileName || fileName.trim().equals("")) { //如果不设置文件名,则默认fileName = new String((fileName + new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(), StandardCharsets.UTF_8);}response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");Workbook workbook = new XSSFWorkbook();// 创建一个单元格样式CellStyle titleCellStyle = workbook.createCellStyle();titleCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());//25%灰色titleCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);titleCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());titleCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());titleCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());titleCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());// 设置边框样式为细线titleCellStyle.setBorderBottom(BorderStyle.THIN);titleCellStyle.setBorderTop(BorderStyle.THIN);titleCellStyle.setBorderLeft(BorderStyle.THIN);titleCellStyle.setBorderRight(BorderStyle.THIN);titleCellStyle.setAlignment(HorizontalAlignment.CENTER);titleCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 创建一个单元格样式CellStyle dataCellStyle = workbook.createCellStyle();dataCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());dataCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());// 设置边框样式为细线dataCellStyle.setBorderLeft(BorderStyle.THIN);dataCellStyle.setBorderRight(BorderStyle.THIN);// 创建一个单元格样式CellStyle lastCellStyle = workbook.createCellStyle();lastCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());lastCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());lastCellStyle.setBorderBottom(BorderStyle.THIN);// 设置边框样式为细线lastCellStyle.setBorderLeft(BorderStyle.THIN);lastCellStyle.setBorderRight(BorderStyle.THIN);lastCellStyle.setBorderBottom(BorderStyle.THIN);for (int i = 0; i < excelExports.size(); i++) {ExcelExport excelExport = excelExports.get(i);List<String> headList = excelExport.getTitle();String sheetName = excelExport.getSheetName();List<LinkedHashMap<String, Object>> dataList = excelExport.getDataList();Sheet sheet = workbook.createSheet(sheetName);// 创建数据行Row titleRow = sheet.createRow(0);titleRow.setHeightInPoints(500 / 20);for (int j = 0; j < headList.size(); j++) {Cell cell1 = titleRow.createCell(j);cell1.setCellStyle(titleCellStyle);cell1.setCellValue(headList.get(j));}Map<String, Integer> columnWidthMap = new HashMap<>();for (int k = 0; k < dataList.size(); k++) {Row dataRow = sheet.createRow(k + 1);for (int j = 0; j < headList.size(); j++) {String title = headList.get(j);LinkedHashMap<String, Object> stringObjectLinkedHashMap = dataList.get(k);Object value = stringObjectLinkedHashMap.get(title);Cell cell = dataRow.createCell(j);if (k == (dataList.size() - 1)) {cell.setCellStyle(lastCellStyle);} else {cell.setCellStyle(dataCellStyle);}cell.setCellValue(value == null ? null : value.toString());if (null != value) {// 计算内容的字符长度int charLength = value.toString().length();// 设置一个最大宽度(以字符为单位)int maxWidthInChars = 0;// 根据内容长度和最大宽度计算列宽// 注意:Excel的列宽单位是字符宽度的1/256,因此需要将字符数乘以256// 但由于内容可能包含非单字节字符(如中文),这里简化处理,只考虑ASCII字符宽度// 如果需要更精确的处理,可以考虑使用FontMetrics来计算实际渲染宽度int columnWidth = (int) (Math.max(charLength, maxWidthInChars) * 256);if (columnWidthMap.containsKey(title)) {Integer width = columnWidthMap.get(title);if (width < columnWidth) {columnWidthMap.put(title, columnWidth);}} else {columnWidthMap.put(title, columnWidth);}}}}for (int j = 0; j < headList.size(); j++) {String title = headList.get(j);int width = columnWidthMap.getOrDefault(title,COLUMN_MIN_WIDTH);if (width > COLUMN_MAX_WIDTH) { //防止太长width = COLUMN_MAX_WIDTH;} else if (width < COLUMN_MIN_WIDTH) {width = COLUMN_MIN_WIDTH;}sheet.setColumnWidth(j, width);log.info("列:" + j + ",标题:" + title + ",宽度:" + width);
//                    sheet.autoSizeColumn(j);//自动行宽}}workbook.write(response.getOutputStream());workbook.close();
//            servletOutputStream.flush();} catch (IOException e) {throw new IOException(e.toString());} finally {}}public static void exportExcel2(List<String> headList, List<Object[]> dataList, String sheetName, String fileName, HttpServletResponse response)throws IOException {try {response.setContentType("multipart/form-data");response.setCharacterEncoding("utf-8");if (null == fileName || fileName.trim().equals("")) { //如果不设置文件名,则默认fileName = new String((fileName + new SimpleDateFormat("yyyy-MM-dd").format(new Date())).getBytes(), StandardCharsets.UTF_8);}response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");Workbook workbook = new XSSFWorkbook();// 创建一个单元格样式CellStyle titleCellStyle = workbook.createCellStyle();titleCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());//25%灰色titleCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);titleCellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());titleCellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());titleCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());titleCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());// 设置边框样式为细线titleCellStyle.setBorderBottom(BorderStyle.THIN);titleCellStyle.setBorderTop(BorderStyle.THIN);titleCellStyle.setBorderLeft(BorderStyle.THIN);titleCellStyle.setBorderRight(BorderStyle.THIN);titleCellStyle.setAlignment(HorizontalAlignment.CENTER);titleCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 创建一个单元格样式CellStyle dataCellStyle = workbook.createCellStyle();dataCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());dataCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());// 设置边框样式为细线dataCellStyle.setBorderLeft(BorderStyle.THIN);dataCellStyle.setBorderRight(BorderStyle.THIN);// 创建一个单元格样式CellStyle lastCellStyle = workbook.createCellStyle();lastCellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());lastCellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());lastCellStyle.setBorderBottom(BorderStyle.THIN);// 设置边框样式为细线lastCellStyle.setBorderLeft(BorderStyle.THIN);lastCellStyle.setBorderRight(BorderStyle.THIN);lastCellStyle.setBorderBottom(BorderStyle.THIN);Sheet sheet = workbook.createSheet(sheetName);// 创建数据行Row titleRow = sheet.createRow(0);titleRow.setHeightInPoints(500 / 20);
//                titleRow.setHeight((short)500);for (int j = 0; j < headList.size(); j++) {Cell cell1 = titleRow.createCell(j);cell1.setCellStyle(titleCellStyle);cell1.setCellValue(headList.get(j));}Map<String, Integer> columnWidthMap = new HashMap<>();for (int k = 0; k < dataList.size(); k++) {Row dataRow = sheet.createRow(k + 1);for (int j = 0; j < headList.size(); j++) {String title = headList.get(j);
//                    LinkedHashMap<String, Object> stringObjectLinkedHashMap = dataList.get(k);
//                    Object value = stringObjectLinkedHashMap.get(title);Object value = dataList.get(k)[j];Cell cell = dataRow.createCell(j);if (k == (dataList.size() - 1)) {cell.setCellStyle(lastCellStyle);} else {cell.setCellStyle(dataCellStyle);}cell.setCellValue(value == null ? null : value.toString());if (null != value) {// 计算内容的字符长度int charLength = value.toString().length();// 设置一个最大宽度(以字符为单位)int maxWidthInChars = 0;// 根据内容长度和最大宽度计算列宽// 注意:Excel的列宽单位是字符宽度的1/256,因此需要将字符数乘以256// 但由于内容可能包含非单字节字符(如中文),这里简化处理,只考虑ASCII字符宽度// 如果需要更精确的处理,可以考虑使用FontMetrics来计算实际渲染宽度int columnWidth = (int) (Math.max(charLength, maxWidthInChars) * 256);if (columnWidthMap.containsKey(title)) {Integer width = columnWidthMap.get(title);if (width < columnWidth) {columnWidthMap.put(title, columnWidth);}} else {columnWidthMap.put(title, columnWidth);}}}}for (int j = 0; j < headList.size(); j++) {String title = headList.get(j);int width = columnWidthMap.getOrDefault(title,COLUMN_MIN_WIDTH);if (width > COLUMN_MAX_WIDTH) { //防止太长width = COLUMN_MAX_WIDTH;} else if (width < COLUMN_MIN_WIDTH) {width = COLUMN_MIN_WIDTH;}sheet.setColumnWidth(j, width);
//                log.info("列:" + j + ",宽度:" + width);log.info("列:" + j + ",标题:" + title + ",宽度:" + width);
//                    sheet.autoSizeColumn(j);//自动行宽}workbook.write(response.getOutputStream());workbook.close();
//            servletOutputStream.flush();} catch (IOException e) {throw new IOException(e.toString());} finally {
//            if (servletOutputStream != null) {
//                servletOutputStream.close();
//            }}}/*** 导出Excel** @param dataList  数据集合* @param sheetName Excel工作表名称* @param fileName  文件名* @param response  响应对象* @throws IOException*/public static void exportExcel3(List<ColumnData> dataList, String sheetName, String fileName, HttpServletResponse response)throws IOException {List<String> headList = new ArrayList<>();int maxColumn = 0;for (ColumnData columnData : dataList) {headList.add(columnData.getTitle());maxColumn = Math.max(maxColumn, columnData.getValues().size());}int titleLength = headList.size();List<Object[]> dataList2 = new ArrayList<>();for (int i = 0; i < maxColumn; i++) {Object[] objects = new Object[titleLength];for (int j = 0; j < titleLength; j++) {ColumnData columnData = dataList.get(j);Object obj = getDataFromColumnData(columnData, i);objects[j] = obj;}dataList2.add(objects);}exportExcel2(headList, dataList2, sheetName, fileName, response);}private static Object getDataFromColumnData(ColumnData columnData, int index) {List values = columnData.getValues();if (index < values.size()) {return values.get(index);}return null;}
}
public class ColumnData {/*** 标题*/private String title;/*** 竖直的数据*/private List values;public String getTitle() {return title;}public void setTitle(String title) {this.title = title;}public List getValues() {return values;}public void setValues(List values) {this.values = values;}
}
@Setter
@Getter
public class ExcelExport {/*** 页面名称*/private String sheetName;/*** 标题*/private List<String> title;/*** 数据内容*/List<LinkedHashMap<String, Object>> dataList;
}
  1. 导出示例
@GetMapping("/exportExcel2")public void exportExcel2(HttpServletRequest request, HttpServletResponse response) throws IOException {ExcelExport excelExport = new ExcelExport();excelExport.setSheetName("测试");excelExport.setTitle(Arrays.asList("用户名", "地址"));List<LinkedHashMap<String, Object>> dataList = new ArrayList();{LinkedHashMap<String, Object> map = new LinkedHashMap();map.put("用户名","test1");map.put("地址","长安");dataList.add(map);}{LinkedHashMap<String, Object> map = new LinkedHashMap();map.put("用户名","test2");map.put("地址","静海");dataList.add(map);}excelExport.setDataList(dataList);MyExcelExportUtils.exportExcel(Arrays.asList(excelExport), "test", response);}

运行结果
在这里插入图片描述


http://www.ppmy.cn/server/166710.html

相关文章

实在RPA案例|视源股份:驱动20+核心场景数字化升级,组织效能提升超80%

广州视源电子科技股份有限公司&#xff08;以下简称 “视源股份”&#xff0c;股票代码&#xff1a;002841.SZ&#xff09;是广东省大型上市企业&#xff0c;旗下产品常年占据全国份额第一&#xff0c;成功孵出 “液晶电视主控板卡、希沃&#xff08;seewo&#xff09;教育交互…

Hive之最新方式MySQL5.7 安装

检查是否已经安装 mysql&#xff08;两种方式&#xff09; [rootmaster ~]# rpm -qa | grep mysql [rootmaster ~]# yum list installed | grep mysqlcentos 7 下需要删除 mariadb检查&#xff1a; [rootmaster ~]# rpm -qa | grep mariadb删除如下&#xff1a;强制删除 如果…

第 10 天:UE5 交互系统,拾取物品 触发机关!

&#x1f3af; 目标&#xff1a; ✅ 理解 UE5 交互系统&#xff08;Interaction System&#xff09; ✅ 使用 C 让玩家拾取物品 ✅ 创建交互触发器&#xff08;Trigger&#xff09;激活机关 ✅ 使用射线检测&#xff08;Raycast&#xff09;触发交互 1️⃣ UE5 交互系统概述 …

Excel 笔记

实际问题记录 VBA脚本实现特殊的行转列 已知&#xff1a;位于同一Excel工作簿文件中的两个工作表&#xff1a;Sheet1、Sheet2。 问题&#xff1a;现要将Sheet2中的每一行&#xff0c;按Sheet1中的样子进行转置&#xff1a; Sheet2中每一行的黄色单元格&#xff0c;为列头。…

Spring 中的设计模式详解

控制反转(IoC)和依赖注入(DI) IoC(Inversion of Control,控制反转) 是 Spring 中一个非常非常重要的概念&#xff0c;它不是什么技术&#xff0c;而是一种解耦的设计思想。IoC 的主要目的是借助于“第三方”(Spring 中的 IoC 容器) 实现具有依赖关系的对象之间的解耦(IOC 容器…

R语言 文本分析 天龙八部

起因, 目的: 前面有人对 “倚天屠龙记” 进行分析,我这里只是进行模仿而已。 完整的文件, 已经绑定了,反正读者可以找一下。 案例背景 小说《天龙八部》是金庸先生所著的武侠小说,也是“射雕三部曲”的前传。全书共50章,字数超过一百万字。故事发生在北宋末年,以大理…

如何在Kickstart自动化安装完成后ISO内拷贝文件到新系统或者执行命令

如何在Kickstart自动化安装完成后ISO内拷贝文件到新系统或者执行命令 需求 在自动化安装操作系统完成后&#xff0c;需要对操作系统进行配置需要拷贝一些文件到新的操作系统中需要运行一些脚本 问题分析 Linux安装操作系统时&#xff0c;实际上是将ISO镜像文件中的操作系统…

windows10 wsa 安卓子系统终结版

windows10 wsa 安卓子系统终结版 链接&#xff1a;https://pan.xunlei.com/s/VOIdoPPmqdUcgw3daFSbh2dAA1?pwdbe3r# windows10 wsa 安卓子系统终结版&#xff0c;包含三个文件. 1: windows10 wsa v2407.40000.4.0 x64 安卓子系统终结版。 2: Apk lnstaller v1.7 用于识别A…