Java动态生成excel模板、和动态模板数据导出
1、添加依赖
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>4.0.0</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>4.0.0</version>
</dependency>
<dependency><groupId>com.monitorjbl</groupId><artifactId>xlsx-streamer</artifactId><version>2.1.0</version>
</dependency>
2、导出excel工具类
package com.shucha.deveiface.biz.utils;import com.monitorjbl.xlsx.StreamingReader;
import com.sdy.common.model.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@Slf4j
public class ExcelUtil {/*** 数据导出成 Excel 数据格式** @param headList 表头信息 (为null 或者 size() == 0 证明不存在)* @param dataList 数据信息* @return 结果数组*/public static byte[] exportExcel(List<String> headList, List<Map<String, Object>> dataList, String xlsType) throws BizException {byte[] bytes = null;try (Workbook workbook = StringUtils.endsWithIgnoreCase(xlsType, "xlsx") ? new XSSFWorkbook() : new HSSFWorkbook();ByteArrayOutputStream os = new ByteArrayOutputStream()) {int size = 65530;
// int sheetCount = 0;
// if (dataList.size() < size) {
//
// }int sheetCount = dataList == null ? 0 : (dataList.size() < size ? 1 : (dataList.size() % size > 0 ? (dataList.size() / size) + 1 : dataList.size() / size));for (int i = 0; i < sheetCount; i++) {Sheet sheet = workbook.createSheet("sheet" + i);sheet.setDefaultColumnWidth(13);int rowIndex = 0;if (headList != null && headList.size() > 0) {writerHeader(headList, sheet);rowIndex++;}int end = dataList.size() > (size * (i + 1)) ? size : dataList.size();writerData(dataList.subList(i * size, end), headList, sheet, rowIndex);}workbook.write(os);bytes = os.toByteArray();} catch (Exception e) {throw new BizException("" + e);}return bytes;}// 写入本地文件 防止内存溢出public static void write(List<String> headList, List<Map<String, Object>> dataList, String xlsxPath, Integer size) throws BizException {File file = new File(xlsxPath);
// if (file.exists()) {
// file.delete();
// }try (SXSSFWorkbook workbook = new SXSSFWorkbook();FileOutputStream outputStream = new FileOutputStream(file)) {int sheetCount = dataList == null ? 0 : (dataList.size() < size ? 1 : (dataList.size() % size > 0 ? (dataList.size() / size) + 1 : dataList.size() / size));for (int i = 0; i < sheetCount; i++) {Sheet sheet = workbook.createSheet(i + "");sheet.setDefaultColumnWidth(13);int rowIndex = 0;if (headList != null && headList.size() > 0) {writerHeader(headList, sheet);rowIndex++;}int end = dataList.size() > (size * (i + 1)) ? size : dataList.size();writerData(dataList.subList(i * size, end), headList, sheet, rowIndex);}workbook.write(outputStream);} catch (Exception e) {log.error("", e);throw new BizException("" + e);}}//读取本地文件 防止内存溢出public static List<Map<String, Object>> readExcel(File file, Integer size, Integer current) throws BizException {try (InputStream is = new FileInputStream(file);Workbook workbook = StreamingReader.builder().rowCacheSize(100).bufferSize(4096).open(is)) {List<String> headerList = new ArrayList<>();List<Map<String, Object>> dataList = new ArrayList<>();for (Sheet sheet : workbook) {log.info(sheet.getSheetName());int start = (current * size) + 1;int end = start + 10;int i = 0;for (Row row : sheet) {if (i == 0) {for (Cell cell : row) {headerList.add(cell.getStringCellValue());}} else if (i > start && i <= end) {Map<String, Object> map = new HashMap<>();int j = 0;for (Cell cell : row) {map.put(headerList.get(j), cell.getStringCellValue());j++;}dataList.add(map);} else if (i > end) {break;}i++;}}return dataList;} catch (Exception e) {log.error("", e);throw new BizException("" + e);}}// public static void writeExcel(List<String> headList, List<Map<String, Object>> dataList, String xlsxPath, Integer size) throws BizException {
// File file = new File(xlsxPath);
// if (file.exists()) {
// file.delete();
// }
// try (SXSSFWorkbook workbook = new SXSSFWorkbook();
// FileOutputStream outputStream = new FileOutputStream(file)) {
// int sheetCount = dataList == null ? 0 : (dataList.size() < size ? 1 : (dataList.size() % size > 0 ? (dataList.size() / size) + 1 : dataList.size() / size));
// for (int i = 0; i < sheetCount; i++) {
// Sheet sheet = workbook.createSheet(i + "");
// sheet.setDefaultColumnWidth(13);
// int rowIndex = 0;
// if (headList != null && headList.size() > 0) {
// writerHeader(headList, sheet);
// rowIndex++;
// }
// int end = dataList.size() > (size * (i + 1)) ? size : dataList.size();
// writerData(dataList.subList(i * size, end), headList, sheet, rowIndex);
// }
// workbook.write(outputStream);
// } catch (Exception e) {
// throw new BizException("" + e);
// }
// }
//
// public static void main(String[] args) throws BizException {List<String> headList = new ArrayList<>();List<Map<String, Object>> dataList = new ArrayList<>();headList.add("name");headList.add("value");for (int a = 0; a < 70000; a++) {Map<String, Object> map1 = new HashMap<>();map1.put("name", "测试name" + a);map1.put("value", "测试value" + a);dataList.add(map1);}write(headList, dataList, "/opt/1111.xlsx", 500000);List<Map<String, Object>> maps = readExcel(new File("D:/opt/1111.xlsx"), 10, 50);maps.size();
// Integer a = 0;
// for (int i = 0; i < 10; i++) {
// ExcelUtil excelUtil = new ExcelUtil();
// excelUtil.test(a);
// System.out.println(a);
// }
//
// }
//
// public void test(Integer a) {
// a = a + 1;
// }// public static void main(String[] args) throws Exception {
// String rootPath = "D:/";
// createImage("检察院看板", new Font("宋体", Font.PLAIN, 30), Paths.get(rootPath, "b" + 4000 + ".png").toFile());
// }// private static int[] getWidthAndHeight(String text, Font font) {
// Rectangle2D r = font.getStringBounds(text, new FontRenderContext(
// AffineTransform.getScaleInstance(1, 1), false, false));
// int unitHeight = (int) Math.floor(r.getHeight());//
// // 获取整个str用了font样式的宽度这里用四舍五入后+1保证宽度绝对能容纳这个字符串作为图片的宽度
// int width = (int) Math.round(r.getWidth()) + 1;
// // 把单个字符的高度+3保证高度绝对能容纳字符串作为图片的高度
// int height = unitHeight + 3;
// System.out.println("width:" + width + ", height:" + height);
// return new int[]{width, height};return new int[]{190, 28};
// }
//
// // 根据str,font的样式以及输出文件目录
// public static void createImage(String text, Font font, File outFile)
// throws Exception {
// // 获取font的样式应用在str上的整个矩形
// int[] arr = getWidthAndHeight(text, font);
// int width = arr[0];
// int height = arr[1];
// // 创建图片
// BufferedImage image = new BufferedImage(width, height,
// BufferedImage.TYPE_INT_BGR);//创建图片画布
// Graphics g = image.getGraphics();
// g.setColor(Color.WHITE); // 先用白色填充整张图片,也就是背景
// g.fillRect(0, 0, width, height);//画出矩形区域,以便于在矩形区域内写入文字
// g.setColor(Color.black);// 再换成黑色,以便于写入文字
// g.setFont(font);// 设置画笔字体
// g.drawString(text, 0, font.getSize());// 画出一行字符串
// g.drawString(text, 0, 2 * font.getSize());// 画出第二行字符串,注意y轴坐标需要变动
// g.dispose();
// ImageIO.write(image, "png", outFile);// 输出png图片
// }public static byte[] exportExcelHead(List<String> headList, String xlsType) throws BizException {byte[] bytes = null;try (Workbook workbook = StringUtils.endsWithIgnoreCase(xlsType, "xlsx") ? new XSSFWorkbook() : new HSSFWorkbook();ByteArrayOutputStream os = new ByteArrayOutputStream()) {Sheet sheet = workbook.createSheet(0 + "");sheet.setDefaultColumnWidth(13);if (headList != null && headList.size() > 0) {writerHeader(headList, sheet);}workbook.write(os);bytes = os.toByteArray();} catch (Exception e) {throw new BizException("" + e);}return bytes;}/*** 写表头** @param headList 表头List* @param sheet sheet*/public static void writerHeader(List<String> headList, Sheet sheet) {Row row = sheet.createRow(0);row.setHeightInPoints(21);RichTextString text;for (int i = 0; i < headList.size(); i++) {Cell cell = row.createCell((short) i);text = new XSSFRichTextString(headList.get(i));cell.setCellValue(text.toString());}}/*** 写数据** @param dataList 数据* @param headList 表头* @param sheet sheel* @param rowIndex 单元格索引*/public static void writerData(List<Map<String, Object>> dataList, List<String> headList, Sheet sheet, int rowIndex) {Row row;Cell cell;RichTextString text;for (int i = 0; i < dataList.size(); i++) {row = sheet.createRow(rowIndex + i);Map<String, Object> datas = dataList.get(i);for (int j = 0; j < headList.size(); j++) {cell = row.createCell(j);Object value = datas.get(headList.get(j));String data = value == null ? "" : String.valueOf(value);text = new XSSFRichTextString(data);cell.setCellValue(text);}}}public static Object getValue(Cell cell) {Object cellValue = "";if (cell != null) {//必须使用switch来获取单元格数据,否则会报错,除非确保execl所有单元格的数据类型一致switch (cell.getCellType()) {case BOOLEAN://获取布尔型数据cellValue = cell.getBooleanCellValue();break;case BLANK://获取空值cellValue = cell.getBooleanCellValue();break;case ERROR://获取错误单元格cellValue = cell.getErrorCellValue();break;case NUMERIC://获取数字类型的数据cellValue = cell.getNumericCellValue();break;case STRING://获取字符串cellValue = cell.getStringCellValue();break;}} else {cellValue = "";}return cellValue;}}
3、测试调用生成excel文件
@GetMapping("/template")@ApiOperation(value = "动态生成excel模板")public void templateDerive(HttpServletResponse response) throws BizException {List<String> paramList = new ArrayList<>();for (int i=0;i<5;i++) {paramList.add("标题名称"+ i);}try {byte[] bytes = ExcelUtil.exportExcelHead(paramList, "xlsx");response.setContentType("application/vnd.ms-excel;charset=UTF-8");response.setCharacterEncoding("utf-8");String filename = "动态导出模板.xlsx";response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));response.getOutputStream().write(bytes);} catch (Exception e) {throw new BizException("模板文件生成失败!原因:" + e);}}@GetMapping("/templateExcelData")@ApiOperation(value = "导出模板和数据")public void templateExcelData(HttpServletResponse response) throws BizException {List<String> headList = new ArrayList<>();
// for (int i=0;i<5;i++) {
// headList.add("标题名称"+ i);
// }
// List<String> headList = new ArrayList<>();List<Map<String, Object>> dataList = new ArrayList<>();headList.add("name");headList.add("value");for (int a = 0; a < 50; a++) {Map<String, Object> map1 = new HashMap<>();map1.put("name", "测试name" + a);map1.put("value", "测试value" + a);dataList.add(map1);}
// List<Map<String, Object>> dataLis = new ArrayList<>();
// for (int j=0;j<5;j++){
// Map<String, Object> map = new HashMap<>();
// map.put("name","数据名称"+j);
// dataLis.add(map);
// }try {byte[] bytes = ExcelUtil.exportExcel(headList, dataList, "xlsx");response.setContentType("application/vnd.ms-excel;charset=UTF-8");response.setCharacterEncoding("utf-8");String filename = "动态导出模板和数据.xlsx";response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));response.getOutputStream().write(bytes);} catch (Exception e) {throw new BizException("模板文件生成失败!原因:" + e);}}
Java动态生成excel模板、和动态模板数据导出相关推荐
- Java动态生成excel模板文件(包含列下拉)
1.添加依赖 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency><gr ...
- word文档中动态生成excel表格(基金公告系列讲解)
1.本博文仅为了将之前工作中动态生成XBRL文件需求中word文档动态生成excel部分进行了实现(虽然隔着时间比较久),闲暇之余的考虑,应对大批量文件生成时可采用定时任务+多线程技术+redis队列 ...
- 通过表单设计器动态生成数据库表以及动态查询的功能实现
表单设计器动态生成数据库表以及动态查询的功能实现 前言 1. 功能实现 1.1 效果说明 1.2 功能流程图 1.3 具体后端实现 1.4 实现效果 2. 尾声 前言 前两天安排了作为Java小码农的 ...
- VUE之Vxe-table动态生成多级表头及后端返回数据的处理
需求: 1.第一列为正常列: 2.第二列开始为动态生成列(根据接口返回数据生成): 3.最后一列为编辑列. 步骤: 写入动态html模板 <vxe-tableid="prdReques ...
- 动态创建excel文件,动态合并单元格并提供下载
1.动态生成excel的原因 ** 出现的效果: ** 员工姓名没有自动合并单元格,在http://jxls.sourceforge.net/reference/xls_area.html 上面找了半 ...
- ajax 怎么input赋值,jQuery ajax请求返回list数据动态生成input标签,并把list数据赋值到input标签...
jQuery ajax请求返回list数据动态生成input标签,并把list数据赋值到input标签 发布于 2016-11-25 16:26:40 | 111 次阅读 | 评论: 0 | 来源: ...
- Java后台生成Excel表格
Java后台生成Excel表格 功能简述 需求 目标 实现 1.首先在项目中导入jxl相关jar包,并引入 2.编写代码 3.结果 后记 功能简述 由于公司业务需求,我需要实现一个完全通过Java后台 ...
- java 实现生成excel表头,A-Z;AA-ZZ;AAA-ZZZ支持无限,数字转字母 ,字母转数字
java 实现生成excel表头,A-Z;AA-ZZ;AAA-ZZZ支持无限,数字转字母 ,字母转数字 public static void main(String[] args) {String k ...
- 动态生成洛谷个人练习/估值数据
最近有人问我怎么才能动态生成洛谷个人练习/估值数据,下面给大家讲一下 首先打开Google Chrome浏览器,输入网址 http://luogu.wao3.cn/ 输入自己的洛谷UID 然后调试选项 ...
- 不生成Excel文件,将Datatable数据 Response.write 输出生成Excel (转载)
不生成Excel文件,将Datatable数据 Response.write 输出生成Excel using System; using System.Data; using System.Confi ...
最新文章
- 百度王海峰:多模态深度语义理解将让AI更深地理解真实世界
- 牛逼哄哄的 Lambda 表达式,简洁优雅就是生产力!
- Linux 第70天 mariadb transaction, log
- vue实现进入页面表单聚焦
- BitSet 数字排序
- python100个免费实例-Python实例100个(基于最新Python3.7版本)
- 软件测试需求人才越来越多
- Bishops Alliance—— 最大上升子序列
- redmine安装指引
- 系统优化-----sysctl.conf文件内核设置参数详解
- 交换机配置工具_二层网管交换机应用—环路检测
- 2014-03-18
- 2021-09-07912. 排序数组
- cuda 和 cudnn 下载与安装
- BBS论坛管理系统软件建模实验
- 数学建模学习(24): 排队论模型完整详细讲解,数学与案例结合,lingo软件搭配,数学不好也能学会!
- Win11 安装 Linux 子系统
- 验证数据是否满足正态分布——Q-Q图和P-P图
- IBM PVM Study之--IBM PVM技术概述
- 2022 CCF中国软件大会(CCF ChinaSoft)“AI软件系统工程化技术与规范”论坛成功召开...