Poi模板技术

2024-08-26 14:48
文章标签 模板 技术 poi

本文主要是介绍Poi模板技术,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Poi模板技术导入导出Excel

在我们的工作中, 也经常会用到Poi模板技术操作Excel文件数据, 而且不同的应用场景对Excel表格的单元格格式和合并操作都需要写大量的代码调试, 比较麻烦. 通过模板技术将自定义格式的Excel文件模板存放在服务器指定位置, 然后读取数据或者填充数据都使用该模板的样式, 不用自己去编写代码设置样式, 使用非常方便. 同样的, 本篇不会写入门案例, 只是记录自己工作或学习中封装的工具方法.

说明: 以下代码基于poi-3.17版本实现, poi-3.17及以上版本相比3.17以下版本样式设置的api改动比较大, 可能存在数据类型获取api过时或报错等, 请参考 Poi版本升级优化

1. 自定义注解

借鉴EasyPoiEasyExcel的使用方式, 都通过注解开发方法来导出指定的字段或读取指定的属性数据. 下面我也自定义了一个简单的注解类.

com.poi.anno.ExcelAttr

package com.poi.anno;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** 自定义注解, 用于标识需要导出到Excel文件的属性字段*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelAttr {int sort() default 0;
}

2. 定义数据模型

将导入或导出的数据与pojo实体类关联, 因为要写getter, setter方法, 我使用lombok自动生成.

lombok依赖

<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.20</version><optional>true</optional>
</dependency>

com.poi.entity.Employee

package com.poi.entity;import com.poi.anno.ExcelAttr;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;/*** 类描述:数据模型, 员工信息* @Author wang_qz* @Date 2021/8/14 10:11* @Version 1.0*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Employee {@ExcelAttr(sort = 0)private int id;@ExcelAttr(sort = 1)private String name;@ExcelAttr(sort = 2)private String empno;@ExcelAttr(sort = 3)private int age;@ExcelAttr(sort = 4)private String sex;@ExcelAttr(sort = 5)private String job;@ExcelAttr(sort = 6)private int departid;
}

3. 大数据模板导入

3.1 导入Excel公共方法

com.poi.util.PoiTemplateUtil#importExcel

public List<T> importExcel(Map<String, Object> params, InputStream inputStream, Class<T> clazz) throws Exception {String fileType = (String) params.get("fileType");fileType = Objects.equals("xls", fileType) ? fileType : "xlsx";Workbook workbook = Objects.equals("xls", fileType) ? new HSSFWorkbook(inputStream) : new XSSFWorkbook(inputStream);Sheet sheet = workbook.getSheetAt(0);int lastRowNum = sheet.getLastRowNum();List<T> dataList = new ArrayList<>();for (int i = 1; i <= lastRowNum; i++) {Row row = sheet.getRow(i);short lastCellNum = row.getLastCellNum();// 获取单元格的值并存入objs中Object[] objs = new Object[lastCellNum];for (int j = 0; j < lastCellNum; j++) {Cell cell = row.getCell(j);Object value = getCellValue(cell);objs[j] = value;}T t = clazz.newInstance();// 反射设置属性值Field[] declaredFields = clazz.getDeclaredFields();for (int k = 0; k < declaredFields.length; k++) {Field field = declaredFields[k];field.setAccessible(true);// 获取被自定义注解ExcelAttr标识的字段ExcelAttr anno = field.getAnnotation(ExcelAttr.class);if (anno != null) {// 获取设置的字段排序int sort = anno.sort();if (sort == k) {String fieldType = field.getType().getName();final Object value = objs[k];if (Objects.equals("int", fieldType) || Objects.equals("Integer", fieldType)) {field.setInt(t, Integer.parseInt(value.toString()));} else if (Objects.equals("double", fieldType) ||Objects.equals("Double", fieldType)) {field.setDouble(t, Double.parseDouble(value.toString()));} else {field.set(t, value);}}}}dataList.add(t);}return dataList;
}

3.2 获取单元格数据类型

com.poi.util.PoiTemplateUtil#getCellValue

/*** 获取单元格的不同数据类型的值* @param cell* @return*/
public static Object getCellValue(Cell cell) {Object cellValue = ""; // 每个单元格的值if (cell != null) {// 数据类型判断, 获取不同类型的数据switch (cell.getCellTypeEnum()) {case NUMERIC: // 数字类型// 日期格式的数字if (HSSFDateUtil.isCellDateFormatted(cell)) {// 日期cellValue = cell.getDateCellValue();} else {// 不是日期格式的数字, 返回字符串格式cellValue = cell.getRichStringCellValue().toString();}break;case STRING: // 字符串cellValue = cell.getStringCellValue();break;case BOOLEAN: // 布尔cellValue = cell.getBooleanCellValue();break;case FORMULA: // 公式cellValue = String.valueOf(cell.getCellFormula());break;case BLANK: // 空cellValue = "";break;case ERROR: // 错误cellValue = "非法字符";break;default:cellValue = "未知类型";break;}}return cellValue;
}

4. 大数据模板导出

com.poi.util.PoiTemplateUtil#exportExcel

/*** 根据模板填充数据生成excel文件* @param params* @param outputStream* @throws Exception*/
public void exportExcel(@NonNull Map<String, Object> params, OutputStream outputStream) throws Exception {List<T> datas = (List<T>) params.get("datas");// "template/excel/template.xls"String template = (String) params.get("template"); int templateDataRowIndex = (int) params.get("templateDataRowIndex");String fileType = template.substring(template.lastIndexOf(".") + 1);fileType = Objects.equals("xls", fileType) ? fileType : "xlsx";InputStream templateStream = PoiTemplateUtil.class.getClassLoader().getResourceAsStream(template);Workbook workbook = Objects.equals("xls", fileType) ? new HSSFWorkbook(templateStream) : new XSSFWorkbook(templateStream);// 获取模板sheetSheet sheet = workbook.getSheetAt(0);// 获取模板数据行Row templateDataRow = sheet.getRow(templateDataRowIndex);// 将模板数据行样式用CellStyle数组存起来,后面填充数据用到该模板数据样式CellStyle[] cellStyles = new CellStyle[templateDataRow.getLastCellNum()];for (int i = 0; i < cellStyles.length; i++) {cellStyles[i] = templateDataRow.getCell(i).getCellStyle();}// 填充数据for (int i = 0; i < datas.size(); i++) {// 创建数据行-跟随模板Row row = sheet.createRow(i + templateDataRowIndex);T t = datas.get(i);Field[] declaredFields = t.getClass().getDeclaredFields();for (int j = 0; j < cellStyles.length; j++) {// 创建单元格Cell cell = row.createCell(j);// 设置单元格样式cell.setCellStyle(cellStyles[j]);for (Field field : declaredFields) {// 获取被@ExcelAttr注解标注且注解的sort=j的的属性field.setAccessible(true);ExcelAttr anno = field.getAnnotation(ExcelAttr.class);if (anno != null) {int sort = anno.sort();if (sort == j) {// 设置单元格的值cell.setCellValue(field.get(t).toString());}}}}}// 生成excel文件到指定位置workbook.write(outputStream);
}

5. 导入导出工具类全部代码

com.poi.util.PoiTemplateUtil

package com.poi.util;import com.poi.anno.ExcelAttr;
import com.poi.entity.Employee;
import lombok.NonNull;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;/*** 类描述:模板导出excel工具类* @Author wang_qz* @Date 2021/8/14 10:30* @Version 1.0*/
public class PoiTemplateUtil<T> {/*** 根据模板填充数据生成excel文件* @param params* @param outputStream* @throws Exception*/public void exportExcel(@NonNull Map<String, Object> params, OutputStream outputStream) throws Exception {List<T> datas = (List<T>) params.get("datas");// "template/excel/template.xls"String template = (String) params.get("template"); int templateDataRowIndex = (int) params.get("templateDataRowIndex");String fileType = template.substring(template.lastIndexOf(".") + 1);fileType = Objects.equals("xls", fileType) ? fileType : "xlsx";InputStream templateStream = PoiTemplateUtil.class.getClassLoader().getResourceAsStream(template);Workbook workbook = Objects.equals("xls", fileType) ? new HSSFWorkbook(templateStream) : new XSSFWorkbook(templateStream);// 获取模板sheetSheet sheet = workbook.getSheetAt(0);// 获取模板数据行Row templateDataRow = sheet.getRow(templateDataRowIndex);// 将模板数据行样式用CellStyle数组存起来,后面填充数据用到该模板数据样式CellStyle[] cellStyles = new CellStyle[templateDataRow.getLastCellNum()];for (int i = 0; i < cellStyles.length; i++) {cellStyles[i] = templateDataRow.getCell(i).getCellStyle();}// 填充数据for (int i = 0; i < datas.size(); i++) {// 创建数据行-跟随模板Row row = sheet.createRow(i + templateDataRowIndex);T t = datas.get(i);Field[] declaredFields = t.getClass().getDeclaredFields();for (int j = 0; j < cellStyles.length; j++) {// 创建单元格Cell cell = row.createCell(j);// 设置单元格样式cell.setCellStyle(cellStyles[j]);for (Field field : declaredFields) {// 获取被@ExcelAttr注解标注且注解的sort=j的的属性field.setAccessible(true);ExcelAttr anno = field.getAnnotation(ExcelAttr.class);if (anno != null) {int sort = anno.sort();if (sort == j) {// 设置单元格的值cell.setCellValue(field.get(t).toString());}}}}}// 生成excel文件到指定位置workbook.write(outputStream);}/*** 大数据模板导入* @param params* @param inputStream* @param clazz* @return* @throws Exception*/public List<T> importExcel(Map<String, Object> params, InputStream inputStream,Class<T> clazz) throws Exception {String fileType = (String) params.get("fileType");fileType = Objects.equals("xls", fileType) ? fileType : "xlsx";Workbook workbook = Objects.equals("xls", fileType) ? new HSSFWorkbook(inputStream) : new XSSFWorkbook(inputStream);Sheet sheet = workbook.getSheetAt(0);int lastRowNum = sheet.getLastRowNum();List<T> dataList = new ArrayList<>();for (int i = 1; i <= lastRowNum; i++) {Row row = sheet.getRow(i);short lastCellNum = row.getLastCellNum();// 获取单元格的值并存入objs中Object[] objs = new Object[lastCellNum];for (int j = 0; j < lastCellNum; j++) {Cell cell = row.getCell(j);Object value = getCellValue(cell);objs[j] = value;}T t = clazz.newInstance();// 反射设置属性值Field[] declaredFields = clazz.getDeclaredFields();for (int k = 0; k < declaredFields.length; k++) {Field field = declaredFields[k];field.setAccessible(true);// 获取被自定义注解ExcelAttr标识的字段ExcelAttr anno = field.getAnnotation(ExcelAttr.class);if (anno != null) {// 获取设置的字段排序int sort = anno.sort();if (sort == k) {String fieldType = field.getType().getName();final Object value = objs[k];if (Objects.equals("int", fieldType) || Objects.equals("Integer", fieldType)) {field.setInt(t, Integer.parseInt(value.toString()));} else if (Objects.equals("double", fieldType) || Objects.equals("Double", fieldType)) {field.setDouble(t, Double.parseDouble(value.toString()));} else {field.set(t, value);}}}}dataList.add(t);}return dataList;}/*** 获取单元格的不同数据类型的值* @param cell* @return*/public static Object getCellValue(Cell cell) {Object cellValue = ""; // 每个单元格的值if (cell != null) {// 数据类型判断, 获取不同类型的数据switch (cell.getCellTypeEnum()) {case NUMERIC: // 数字类型// 日期格式的数字if (HSSFDateUtil.isCellDateFormatted(cell)) {// 日期cellValue = cell.getDateCellValue();} else {// 不是日期格式的数字, 返回字符串格式cellValue = cell.getRichStringCellValue().toString();}break;case STRING: // 字符串cellValue = cell.getStringCellValue();break;case BOOLEAN: // 布尔cellValue = cell.getBooleanCellValue();break;case FORMULA: // 公式cellValue = String.valueOf(cell.getCellFormula());break;case BLANK: // 空cellValue = "";break;case ERROR: // 错误cellValue = "非法字符";break;default:cellValue = "未知类型";break;}}return cellValue;}/*** 造测试数据* @return*/public static List<Employee> getDatas() {List<Employee> datas = new ArrayList<>();for (int i = 1; i <= 10; i++) {Employee employee = Employee.builder().id(Integer.valueOf(i)).departid(i * 100).empno("10000" + i).age(20 + i).sex(i % 2 == 0 ? "男" : "女").job(i % 2 == 0 ? "快递员" : "工程师").name("admin" + i).build();datas.add(employee);}return datas;}
}

6. 数据模板

数据模板就是自己设置好样式的excel文件, 放在项目类路径下, 如下所示:

template/excel/template.xls

image-20210917212806515

7. 单元测试

7.1 测试大数据导入

com.test.poi.PoiTemplateTest#testImportExcel

@Test
public void testImportExcel() throws Exception {String filename = "D:\\study\\excel\\employees.xls";String fileType = filename.substring(filename.lastIndexOf(".") + 1);Map<String, Object> params = new HashMap<>();params.put("fileType", fileType);PoiTemplateUtil util = new PoiTemplateUtil();List<Employee> dataList = util.importExcel(params, new FileInputStream(filename), Employee.class);dataList.forEach(System.out::println);
}

通过控制台日志查看导入数据效果

image-20210917213255884

7.2 测试大数据导出

com.test.poi.PoiTemplateTest#testExportExcel

@Test
public void testExportExcel() throws Exception {Map<String, Object> params = new HashMap<>();params.put("template", "template/excel/template.xls");params.put("templateDataRowIndex", 1); // 模板中第二行是带格式的数据行params.put("datas", getDatas());PoiTemplateUtil util = new PoiTemplateUtil();util.exportExcel(params, new FileOutputStream("D:\\study\\excel\\employees.xls"));
}

com.test.poi.PoiTemplateTest#getDatas

// 测试数据
public static List<Employee> getDatas() {List<Employee> datas = new ArrayList<>();for (int i = 1; i <= 10; i++) {Employee employee = Employee.builder().id(Integer.valueOf(i)).departid(i * 100).empno("10000" + i).age(20 + i).sex(i % 2 == 0 ? "男" : "女").job(i % 2 == 0 ? "快递员" : "工程师").name("admin" + i).build();datas.add(employee);}return datas;
}

导出数据效果

image-20210917213132729

7.3 web端测试

7.3.1 编写controller

com.poi.controller.ExcelController

package com.poi.controller;import com.constant.CSISCONSTANT;
import com.exception.MyException;
import com.poi.entity.Employee;
import com.poi.service.ExcelReaderImpl;
import com.poi.util.PoiTemplateUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;/*** 类描述:文件上传下载* @Author wang_qz* @Date 2021/8/14 21:07* @Version 1.0*/
@Controller
@RequestMapping("/excel")
public class ExcelController {@RequestMapping("/toExcelPage")public String todownloadPage() {return "excelPage";}@RequestMapping("/downloadExcel")public void downloadExcel(HttpServletResponse response) throws Exception {// 模板文件String template = "template/excel/template.xls";// 文件类型 xls  xlsxString fileType = template.substring(template.lastIndexOf("."));// 设置响应头response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");// 设置防止中文名乱码String filename = URLEncoder.encode("employees信息表", "utf-8");// 文件下载方式(附件下载还是在当前浏览器打开)response.setHeader("Content-disposition", "attachment;filename=" + filename +fileType);// 构建写入到excel文件的数据PoiTemplateUtil util = new PoiTemplateUtil();Map<String, Object> params = new HashMap<>();params.put("template", template);params.put("templateDataRowIndex", 1); // 模板中第二行是带格式的数据行params.put("datas", util.getDatas());util.exportExcel(params, response.getOutputStream());}@PostMapping("/uploadExcel")@ResponseBodypublic String uploadExcel(@RequestParam("file") Part part) throws Exception {// 获取上传的文件流InputStream inputStream = part.getInputStream();// 上传文件名称String filename = part.getSubmittedFileName();// 读取ExcelString fileType = filename.substring(filename.lastIndexOf(".") + 1);Map<String, Object> params = new HashMap<>();params.put("fileType", fileType);PoiTemplateUtil util = new PoiTemplateUtil();List<Employee> dataList = util.importExcel(params, inputStream,Employee.class);dataList.forEach(System.out::println);return "upload successful!";}@RequestMapping("/toExcelPage2")public String todownloadPage2() {return "excelPage2";}
}
7.3.1 编写jsp页面

webapp/WEB-INF/jsp/excelPage.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>测试excel文件下载</title>
</head>
<body>
<h3>点击下面链接, 进行excel文件下载</h3>
<a href="<c:url value='/excel/downloadExcel'/>">Excel文件下载</a>
<hr/>
<hr/>
<h3>点击下面按钮, 进行excel文件上传</h3>
<form action="<c:url value='/excel/uploadExcel'/>" method="post" enctype="multipart/form-data"><input type="file" name="file"/><br/><input type="submit" value="上传Excel"/>
</form>
</body>
</html>

启动tomcat, 访问http://localhost:8080/excel/toExcelPage, 进入测试页面:

image-20210917214557918

7.3.4 测试效果

下载结果

image-20210917213132729

上传效果

image-20210917213255884

相关推荐

数据分流写入Excel

Poi版本升级优化

StringTemplate实现Excel导出

Poi模板技术

SAX方式实现Excel导入

DOM方式实现Excel导入

Poi实现Excel导出

EasyExcel实现Excel文件导入导出

EasyPoi实现excel文件导入导出

个人博客

欢迎各位访问我的个人博客: https://www.crystalblog.xyz/

备用地址: https://wang-qz.gitee.io/crystal-blog/

这篇关于Poi模板技术的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1108868

相关文章

Python中高级文本模式匹配与查找技术指南

《Python中高级文本模式匹配与查找技术指南》文本处理是编程世界的永恒主题,而模式匹配则是文本处理的基石,本文将深度剖析PythonCookbook中的核心匹配技术,并结合实际工程案例展示其应用,希... 目录引言一、基础工具:字符串方法与序列匹配二、正则表达式:模式匹配的瑞士军刀2.1 re模块核心AP

springboot自定义注解RateLimiter限流注解技术文档详解

《springboot自定义注解RateLimiter限流注解技术文档详解》文章介绍了限流技术的概念、作用及实现方式,通过SpringAOP拦截方法、缓存存储计数器,结合注解、枚举、异常类等核心组件,... 目录什么是限流系统架构核心组件详解1. 限流注解 (@RateLimiter)2. 限流类型枚举 (

Python实现PDF按页分割的技术指南

《Python实现PDF按页分割的技术指南》PDF文件处理是日常工作中的常见需求,特别是当我们需要将大型PDF文档拆分为多个部分时,下面我们就来看看如何使用Python创建一个灵活的PDF分割工具吧... 目录需求分析技术方案工具选择安装依赖完整代码实现使用说明基本用法示例命令输出示例技术亮点实际应用场景扩

SpringBoot集成EasyPoi实现Excel模板导出成PDF文件

《SpringBoot集成EasyPoi实现Excel模板导出成PDF文件》在日常工作中,我们经常需要将数据导出成Excel表格或PDF文件,本文将介绍如何在SpringBoot项目中集成EasyPo... 目录前言摘要简介源代码解析应用场景案例优缺点分析类代码方法介绍测试用例小结前言在日常工作中,我们经

Qt如何实现文本编辑器光标高亮技术

《Qt如何实现文本编辑器光标高亮技术》这篇文章主要为大家详细介绍了Qt如何实现文本编辑器光标高亮技术,文中的示例代码讲解详细,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录实现代码函数作用概述代码详解 + 注释使用 QTextEdit 的高亮技术(重点)总结用到的关键技术点应用场景举例示例优化建议

Java中的登录技术保姆级详细教程

《Java中的登录技术保姆级详细教程》:本文主要介绍Java中登录技术保姆级详细教程的相关资料,在Java中我们可以使用各种技术和框架来实现这些功能,文中通过代码介绍的非常详细,需要的朋友可以参考... 目录1.登录思路2.登录标记1.会话技术2.会话跟踪1.Cookie技术2.Session技术3.令牌技

Web技术与Nginx网站环境部署教程

《Web技术与Nginx网站环境部署教程》:本文主要介绍Web技术与Nginx网站环境部署教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、Web基础1.域名系统DNS2.Hosts文件3.DNS4.域名注册二.网页与html1.网页概述2.HTML概述3.

Java如何根据word模板导出数据

《Java如何根据word模板导出数据》这篇文章主要为大家详细介绍了Java如何实现根据word模板导出数据,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... pom.XML文件导入依赖 <dependency> <groupId>cn.afterturn</groupId>

Java使用WebView实现桌面程序的技术指南

《Java使用WebView实现桌面程序的技术指南》在现代软件开发中,许多应用需要在桌面程序中嵌入Web页面,例如,你可能需要在Java桌面应用中嵌入一部分Web前端,或者加载一个HTML5界面以增强... 目录1、简述2、WebView 特点3、搭建 WebView 示例3.1 添加 JavaFX 依赖3

POI从入门到实战轻松完成EasyExcel使用及Excel导入导出功能

《POI从入门到实战轻松完成EasyExcel使用及Excel导入导出功能》ApachePOI是一个流行的Java库,用于处理MicrosoftOffice格式文件,提供丰富API来创建、读取和修改O... 目录前言:Apache POIEasyPoiEasyExcel一、EasyExcel1.1、核心特性