Spring Boot集成easypoi快速入门Demo

1.什么是easypoi?

Easypoi功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员就可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板语言(熟悉的表达式语法),完成以前复杂的写法。

2.代码工程

实验目的:实现excel导入和导出

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>springboot-demo</artifactId><groupId>com.et</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>eaypoi</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-spring-boot-starter</artifactId><version>4.1.2</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.40</version></dependency></dependencies>
</project>

HelloWorldController.java

package com.et.easypoi.controller;import com.alibaba.fastjson.JSONObject;
import com.et.easypoi.Util.FileUtil;
import com.et.easypoi.model.GoodType;
import com.et.easypoi.model.Goods;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletResponse;
import java.util.*;@RestController
public class HelloWorldController {@RequestMapping("/hello")public Map<String, Object> showHelloWorld(){Map<String, Object> map = new HashMap<>();map.put("msg", "HelloWorld");return map;}@RequestMapping("/exportExcel")public void export(HttpServletResponse response) throws Exception {//mock datasGoods goods1 = new Goods();List<GoodType>  goodTypeList1 = new ArrayList<>();GoodType goodType1  =  new GoodType();goodType1.setTypeId("apple-1");goodType1.setTypeName("apple-red");goodTypeList1.add(goodType1);GoodType goodType2  =  new GoodType();goodType2.setTypeId("apple-2");goodType2.setTypeName("apple-white");goodTypeList1.add(goodType2);goods1.setNo(110);goods1.setName("apple");goods1.setShelfLife(new Date());goods1.setGoodTypes(goodTypeList1);Goods goods2 = new Goods();List<GoodType>  goodTypeList2 = new ArrayList<>();GoodType goodType21  =  new GoodType();goodType21.setTypeId("wine-1");goodType21.setTypeName("wine-red");goodTypeList2.add(goodType21);GoodType goodType22  =  new GoodType();goodType22.setTypeId("wine-2");goodType22.setTypeName("wine-white");goodTypeList2.add(goodType22);goods2.setNo(111);goods2.setName("wine");goods2.setShelfLife(new Date());goods2.setGoodTypes(goodTypeList2);List<Goods> goodsList = new ArrayList<Goods>();goodsList.add(goods1);goodsList.add(goods2);for (Goods goods : goodsList) {System.out.println(goods);}//exportFileUtil.exportExcel(goodsList, Goods.class,"product.xls",response);}@RequestMapping("/importExcel")public void importExcel() throws Exception {//loal fileString filePath = "C:\\Users\\Dell\\Downloads\\product.xls";//anaysis excelList<Goods> goodsList = FileUtil.importExcel(filePath,0,1,Goods.class);//also use MultipartFile,invoke FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)System.out.println("load data count【"+goodsList.size()+"】row");//TODO save datasfor (Goods goods:goodsList) {JSONObject.toJSONString(goods);}}
}

model

package com.et.easypoi.model;import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.annotation.ExcelCollection;
import lombok.Data;import java.io.Serializable;
import java.util.Date;
import java.util.List;@Data
public class Goods implements Serializable {@Excel(name = "NO",needMerge = true ,width = 20)private Integer no;@Excel(name = "name",needMerge = true ,width = 20)private String name;@Excel(name = "shelfLife",width = 20,needMerge = true ,exportFormat = "yyyy-MM-dd")private Date shelfLife;@ExcelCollection(name = "goodTypes")private List<GoodType> goodTypes;}
package com.et.easypoi.model;import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;/*** @author liuhaihua* @version 1.0* @ClassName GoodType* @Description todo* @date 2024年04月15日 11:02*/
@Data
public class GoodType {@Excel(name = "typeId",  width = 20,height = 8)private String typeId;@Excel(name = "typeName",  width = 20,height = 8)private String typeName;
}

FileUtil

通用工具类,导出和导出封装

package com.et.easypoi.Util;import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.et.easypoi.service.ExcelExportStyler;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;public class FileUtil {public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) throws Exception {ExportParams exportParams = new ExportParams(title, sheetName);exportParams.setCreateHeadRows(isCreateHeader);defaultExport(list, pojoClass, fileName, response, exportParams);}public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName,  HttpServletResponse response) throws Exception {ExportParams exportParams = new ExportParams();exportParams.setStyle(ExcelExportStyler.class); // set styledefaultExport(list, pojoClass, fileName, response, exportParams);}public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response) throws Exception {defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));}public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws Exception {defaultExport(list, fileName, response);}private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws Exception {Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);if (workbook != null);downLoadExcel(fileName, response, workbook);}private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws Exception {OutputStream outputStream=null;try {response.setCharacterEncoding("UTF-8");response.setHeader("content-Type", "application/vnd.ms-excel");response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));outputStream = response.getOutputStream();workbook.write(outputStream);} catch (IOException e) {throw new Exception(e.getMessage());}finally {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) throws Exception {Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);if (workbook != null);downLoadExcel(fileName, response, workbook);}public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass) throws Exception {if (StringUtils.isBlank(filePath)){return null;}ImportParams params = new ImportParams();params.setTitleRows(titleRows);params.setHeadRows(headerRows);List<T> list = null;try {list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);}catch (NoSuchElementException e){throw new Exception("template not null");} catch (Exception e) {e.printStackTrace();throw new Exception(e.getMessage());}return list;}public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass) throws Exception {if (file == null){return null;}ImportParams params = new ImportParams();params.setTitleRows(titleRows);params.setHeadRows(headerRows);List<T> list = null;try {list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);}catch (NoSuchElementException e){throw new Exception("excel file not null");} catch (Exception e) {throw new Exception(e.getMessage());}return list;}
}

ExcelExportStyler

设置表头,单元格样式

package com.et.easypoi.service;import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.entity.params.ExcelForEachParams;
import cn.afterturn.easypoi.excel.export.styler.IExcelExportStyler;
import org.apache.poi.ss.usermodel.*;public class ExcelExportStyler implements IExcelExportStyler {private static final short STRING_FORMAT = (short) BuiltinFormats.getBuiltinFormat("TEXT");private static final short FONT_SIZE_TEN = 10;private static final short FONT_SIZE_ELEVEN = 11;private static final short FONT_SIZE_TWELVE = 12;/*** header style*/private CellStyle headerStyle;/*** title style*/private CellStyle titleStyle;/*** cell style*/private CellStyle styles;public ExcelExportStyler(Workbook workbook) {this.init(workbook);}/*** init** @param workbook*/private void init(Workbook workbook) {this.headerStyle = initHeaderStyle(workbook);this.titleStyle = initTitleStyle(workbook);}@Overridepublic CellStyle getHeaderStyle(short color) {return headerStyle;}@Overridepublic CellStyle getTitleStyle(short color) {return titleStyle;}@Overridepublic CellStyle getStyles(boolean parity, ExcelExportEntity entity) {return styles;}@Overridepublic CellStyle getStyles(Cell cell, int dataRow, ExcelExportEntity entity, Object obj, Object data) {return getStyles(true, entity);}@Overridepublic CellStyle getTemplateStyles(boolean isSingle, ExcelForEachParams excelForEachParams) {return null;}/*** init --HeaderStyle** @param workbook* @return*/private CellStyle initHeaderStyle(Workbook workbook) {CellStyle style = getBaseCellStyle(workbook);style.setFont(getFont(workbook, FONT_SIZE_TWELVE, true));return style;}/*** init-TitleStyle** @param workbook* @return*/private CellStyle initTitleStyle(Workbook workbook) {CellStyle style = getBaseCellStyle(workbook);style.setFont(getFont(workbook, FONT_SIZE_ELEVEN, false));// ForegroundColorstyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());style.setFillPattern(FillPatternType.SOLID_FOREGROUND);return style;}/*** BaseCellStyle** @return*/private CellStyle getBaseCellStyle(Workbook workbook) {CellStyle style = workbook.createCellStyle();style.setBorderBottom(BorderStyle.THIN);style.setBorderLeft(BorderStyle.THIN);style.setBorderTop(BorderStyle.THIN);style.setBorderRight(BorderStyle.THIN);style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);style.setWrapText(true);return style;}/*** Font** @param size* @param isBold* @return*/private Font getFont(Workbook workbook, short size, boolean isBold) {Font font = workbook.createFont();font.setFontName("宋体");font.setBold(isBold);font.setFontHeightInPoints(size);return font;}
}
package com.et.easypoi.service;import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import org.apache.poi.ss.usermodel.CellStyle;public interface IExcelExportStyler {/*** heder style* @param headerColor* @return*/public CellStyle getHeaderStyle(short headerColor);/*** title style* @param color* @return*/public CellStyle getTitleStyle(short color);/*** getstyle* @param Parity* @param entity* @return*/public CellStyle getStyles(boolean Parity, ExcelExportEntity entity);
}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • https://github.com/Harries/springboot-demo

3.测试

启动Spring Boot应用

导出

访问http://127.0.0.1:8088/importExcelb5043bf02dcd0f9dcd291e008581e387.png

导入

访问http://127.0.0.1:8088/importExcel

Goods(no=110, name=apple, shelfLife=Mon Apr 15 13:28:36 CST 2024, goodTypes=[GoodType(typeId=apple-1, typeName=apple-red), GoodType(typeId=apple-2, typeName=apple-white)])
Goods(no=111, name=wine, shelfLife=Mon Apr 15 13:28:36 CST 2024, goodTypes=[GoodType(typeId=wine-1, typeName=wine-red), GoodType(typeId=wine-2, typeName=wine-white)])
load data count【3】row

4.引用

  • http://www.ibloger.net/article/3391.html

  • http://www.liuhaihua.cn/archives/710424.html

  • http://doc.wupaas.com/docs/easypoi/easypoi-1c0u9a1bv66f4

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/624794.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

简单3步,OpenHarmony上跑起ArkUI分布式小游戏

标准系统新增支持了方舟开发框架&#xff08;ArkUI&#xff09;、分布式组网和 FA 跨设备迁移能力等新特性&#xff0c;因此我们结合了这三种特性使用 ets 开发了一款如下动图所示传炸弹应用。 打开应用在通过邀请用户进行设备认证后&#xff0c;用户须根据提示完成相应操作&am…

Adobe AE(After Effects)2015下载地址及安装教程

Adobe After Effects是一款专业级别的视觉效果和动态图形处理软件&#xff0c;由Adobe Systems开发。它被广泛用于电影、电视节目、广告和其他多媒体项目的制作。 After Effects提供了强大的合成和特效功能&#xff0c;可以让用户创建出令人惊艳的动态图形和视觉效果。用户可以…

RK3568 学习笔记 : u-boot 千兆网络功能验证

前言 开发板型号&#xff1a; 【正点原子】 的 RK3568 开发板 使用 虚拟机 ubuntu 20.04 编译 RK3568 Linux SDK&#xff0c;生成镜像&#xff0c;烧写后&#xff0c;Linux 系统正常启动 开启后可以使用 CTRLC 进入 u-boot 本篇验证一下 u-boot 下网络功能 【正点原子】 rk…

分类算法——模型选择与调优(三)

交叉验证 交叉验证&#xff1a;将拿到的训练数据&#xff0c;分为训练和验证集。以下图为例&#xff1a;将数据分成4份&#xff0c;其中 一份作为验证集。然后经过4次&#xff08;组&#xff09;的测试&#xff0c;每次都更换不同的验证集。即得到4组模型的 结果&#xff0c;取…

iOS依赖库版本一致性检测:确保应用兼容性

一、背景 在 iOS 应用开发的世界里&#xff0c;每次 Xcode 更新都带来了新的特性和挑战。最近的 Xcode 15 更新不例外&#xff0c;这次升级引入了对 SwiftUI 的自动强依赖。SwiftUI最低是从 iOS 13 开始支持。 这一变化也带来了潜在的兼容性问题。如果您的项目在升级到 Xcode…

Rust 编写的数据框架:多线程、矢量化查询引擎 | 开源日报 No.226

pola-rs/polars Stars: 25.2k License: MIT polars 是使用 Rust 编写的多线程、支持矢量化查询引擎的数据框架。 基于 Apache Arrow 列式内存模型惰性和急切执行多线程处理SIMD 加速计算查询优化功能强大的表达式 API支持混合流式处理&#xff08;适用于大于内存大小的数据集…

盲盒小程序成为收益“法宝”?盲盒线上如何发展

近年来&#xff0c;盲盒在年轻人中掀起了一股潮玩热风&#xff0c;受到了不少年轻人的青睐&#xff0c;盲盒商品更是在不断创新中&#xff0c;收藏价值逐渐提高。随着市场规模的扩大&#xff0c;越来越多的玩家和商家涌入到了市场中&#xff0c;盲盒的商业模式正在加快发展中。…

AppBuilder升级!工作流编排正式上线!AssistantsAPI开放邀测!

>>【v0.5.3版本】 上线时间&#xff1a;2024/4/14 关键发版信息&#xff1a; 低代码态&#xff1a;新增工作流&#xff0c;低代码制作组件 自定义组件&#xff1a;支持用户自定义创建组件&#xff0c;并被Agent自动编排调用
 工作流框架&#xff1a;组件支持流式编排…

2024 计算机毕业设计之SpringBoot+Vue项目合集(源码+L文+PPT)

各位朋友大家好&#xff0c;有幸与屏幕前你们相识&#xff0c;博主现已经搬砖9年&#xff0c;趁着头发还充裕&#xff0c;希望给大家提供一些编程领域的帮助&#xff0c;深知计算机毕业生这个阶段的崩溃与闹心&#xff0c;让我们共同交流进步。 博主给大家列举了项目合集&#…

pdf做批注编辑工具 最新pdf reader pro3.3.1.0激活版

PDF Reader Pro是一款功能强大的PDF阅读和编辑工具。它提供了多种工具和功能&#xff0c;帮助用户对PDF文档进行浏览、注释、编辑、转换和签名等操作。以下是PDF Reader Pro的一些主要特色&#xff1a; 最新pdf reader pro3.3.1.0激活版下载 多种查看模式&#xff1a;PDF Reade…

Qt 4 QPushButton

Qt 常用控件 QPushButton 实例 Push Button:命令按钮。 入口文件 main.cpp #include "mainwindow.h"#include <QApplication>int main(int argc, char *argv[]) {QApplication a(argc, argv);MainWindow w;w.show();return a.exec(); }头文件 mainwindow.h …

JavaEE:JVM

基本介绍 JVM&#xff1a;Java虚拟机&#xff0c;用于解释执行Java字节码 jdk&#xff1a;Java开发工具包 jre&#xff1a;Java运行时环境 C语言将写入的程序直接编译成二进制的机器语言&#xff0c;而java不想重新编译&#xff0c;希望能直接执行。Java先通过javac把.java…