濮阳免费网站制作/网上销售都有哪些平台

濮阳免费网站制作,网上销售都有哪些平台,北大青鸟职业技术学院简介,北京网站建设团队原文网址:EasyExcel--导入和导出Excel的方法_IT利刃出鞘的博客-CSDN博客 简介 本文介绍SpringBoot整合EasyExcel导入和导出Excel的方法。 使用 Excel导入 实体类 Data public class OrderImportBO {ExcelProperty("订单号")NotBlank(message "…

原文网址:EasyExcel--导入和导出Excel的方法_IT利刃出鞘的博客-CSDN博客

简介

本文介绍SpringBoot整合EasyExcel导入和导出Excel的方法。

使用

Excel导入

实体类

@Data
public class OrderImportBO {@ExcelProperty("订单号")@NotBlank(message = "订单号不能为空")private String scOrderPoolId;@ExcelProperty("金额")private String amount;
}

Controller

@PostMapping("importOrder")
public void importOrder(@RequestPart MultipartFile file) {List<OrderImportBO> orderImportBOList = ExcelUtil.importExcel(file, OrderImportBO.class);
}

Excel导出

 实体类

@Data
public class OrderExportBO {@ExcelProperty("订单号")@NotBlank(message = "订单号不能为空")private String scOrderPoolId;@ExcelProperty("金额")private String amount;
}

Service

List<OrderExportVO> exportVOS = new ArrayList();
ExcelUtil.exportExcel(exportVOS, OrderExportVO.class);

详细代码

依赖

EasyExcel

<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.11</version>
</dependency>

整个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 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.0.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.knife</groupId><artifactId>demo_EasyExcel_SpringBoot</artifactId><version>0.0.1-SNAPSHOT</version><name>demo_EasyExcel_SpringBoot</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.11</version></dependency><dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.3</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.24</version><scope>provided</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.3.0.RELEASE</version></plugin></plugins></build></project>

Excel配置

字符串转换器

package com.knife.excel.handler;import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;public class StringConverter implements Converter<String> {@Overridepublic Class supportJavaTypeKey() {return String.class;}@Overridepublic CellDataTypeEnum supportExcelTypeKey() {return CellDataTypeEnum.STRING;}/*** 将excel对象转成Java对象,这里读的时候会调用*/@Overridepublic String convertToJavaData(CellData cellData, 
ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {return cellData.getStringValue().trim();}/*** 将Java对象转成String对象,写出的时候调用*/@Overridepublic CellData convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {return new CellData(value);}
}

writeHandler

package com.knife.excel.halper;import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;import java.util.HashMap;
import java.util.List;
import java.util.Map;public class ExcelHandler extends AbstractColumnWidthStyleStrategy {private static final int MAX_COLUMN_WIDTH = 255;//因为在自动列宽的过程中,有些设置地方让列宽显得紧凑,所以做出了个判断private static final int COLUMN_WIDTH = 20;private  Map<Integer, Map<Integer, Integer>> CACHE = new HashMap(8);public ExcelHandler() {}@Overrideprotected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);if (needSetWidth) {Map<Integer, Integer> maxColumnWidthMap = (Map)CACHE.get(writeSheetHolder.getSheetNo());if (maxColumnWidthMap == null) {maxColumnWidthMap = new HashMap(16);CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);}Integer columnWidth = this.dataLength(cellDataList, cell, isHead);if (columnWidth >= 0) {if (columnWidth > MAX_COLUMN_WIDTH) {columnWidth = MAX_COLUMN_WIDTH;}else {if(columnWidth<COLUMN_WIDTH){columnWidth =columnWidth*2;}}Integer maxColumnWidth = (Integer)((Map)maxColumnWidthMap).get(cell.getColumnIndex());if (maxColumnWidth == null || columnWidth > maxColumnWidth) {((Map)maxColumnWidthMap).put(cell.getColumnIndex(), columnWidth);writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(),  columnWidth* 256);}}}}private  Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {if (isHead) {return cell.getStringCellValue().getBytes().length;} else {CellData cellData = (CellData)cellDataList.get(0);CellDataTypeEnum type = cellData.getType();if (type == null) {return -1;} else {switch(type) {case STRING:return cellData.getStringValue().getBytes().length;case BOOLEAN:return cellData.getBooleanValue().toString().getBytes().length;case NUMBER:return cellData.getNumberValue().toString().getBytes().length;default:return -1;}}}}public static HorizontalCellStyleStrategy getStyleStrategy(){// 头的策略WriteCellStyle headWriteCellStyle = new WriteCellStyle();// 背景设置为灰色headWriteCellStyle.setFillForegroundColor(IndexedColors.ROYAL_BLUE.getIndex());WriteFont headWriteFont = new WriteFont();headWriteFont.setFontHeightInPoints((short)11);// 字体样式headWriteFont.setFontName("Arial Unicode MS");headWriteFont.setColor(IndexedColors.WHITE.getIndex());headWriteCellStyle.setWriteFont(headWriteFont);//自动换行headWriteCellStyle.setWrapped(false);// 水平对齐方式headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);// 垂直对齐方式headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 内容的策略WriteCellStyle contentWriteCellStyle = new WriteCellStyle();// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定// contentWriteCellStyle.setFillPatternType(FillPatternType.SQUARES);// 背景白色contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());WriteFont contentWriteFont = new WriteFont();// 字体大小contentWriteFont.setFontHeightInPoints((short)11);// 字体样式contentWriteFont.setFontName("宋体");contentWriteCellStyle.setWriteFont(contentWriteFont);//是否换行contentWriteCellStyle.setWrapped(false);//  垂直对齐方式contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);}
}

数据校验

package com.bondex.oms.excel;import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.knife.util.BeanHelper;
import com.knife.util.ValidateUtil;public class ExcelValidateListener<T> extends AnalysisEventListener<T> {@Overridepublic void invoke(T bo, AnalysisContext analysisContext) {// 如果是空行,不处理if (BeanHelper.allFieldAreNull(bo)) {return;}int row = analysisContext.readRowHolder().getRowIndex() + 1;try {// 校验输入字段ValidateUtil.validate(bo);} catch (Exception e) {throw new RuntimeException("第[" + row + "]行数据校验失败:" + e.getMessage());}}@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {}
}

 Bean工具

package com.knife.util;import org.springframework.beans.BeanUtils;
import org.springframework.cglib.core.ReflectUtils;
import org.springframework.util.CollectionUtils;import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;public class BeanHelper {public static <T> List<T> convert(List<?> sources, Class<T> target) {if (CollectionUtils.isEmpty(sources)) {return new ArrayList<>();}List<T> targets = new LinkedList<>();for (Object source : sources) {T t = null;try {t = target.newInstance();} catch (Exception e) {throw new RuntimeException(e);}BeanUtils.copyProperties(source, t);targets.add(t);}return targets;}public static <T> T convert(Object source, Class<T> target) {if (source == null) {return null;}T t;try {t = target.newInstance();} catch (Exception e) {throw new RuntimeException(e);}BeanUtils.copyProperties(source, t);return t;}public static boolean allFieldAreNull(Object o) {Class<?> aClass = o.getClass();PropertyDescriptor[] beanProperties = ReflectUtils.getBeanProperties(aClass);for (PropertyDescriptor beanProperty : beanProperties) {Method readMethod = beanProperty.getReadMethod();try {Object value = readMethod.invoke(o);if (value != null) {return false;}} catch (IllegalAccessException | InvocationTargetException e) {throw new RuntimeException(e);}}return true;}
}

Excel工具类

package com.bondex.oms.util;import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.knife.entity.UserDTO;
import com.knife.util.UserDtoUtils;
import com.knife.excel.helper.ExcelHandler;
import com.knife.excel.helper.ExcelValidateListener;
import com.knife.excel.helper.HeadRowListener;
import com.knife.excel.helper.StringConverter;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;public class ExcelUtil {public static <T> void exportExcel(List<T> dataList,Class<T> tClass) {ServletRequestAttributes servletRequestAttributes =(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();Assert.notNull(servletRequestAttributes, "RequestAttributes不能为null");HttpServletResponse response = servletRequestAttributes.getResponse();Assert.notNull(response, "Response不能为null");ServletOutputStream out = null;try {out = response.getOutputStream();} catch (IOException e) {throw new RuntimeException(e);}String fileName = "测试文件.xlsx";try {// 必须要转一下,否则中文文件名会乱码fileName = URLEncoder.encode(fileName, "UTF-8");} catch (UnsupportedEncodingException e) {throw new RuntimeException(e);}// 通知浏览器以附件的形式下载处理,设置返回头要注意文件名有中文response.setHeader("Content-disposition", "attachment;filename=" + fileName);response.setContentType("multipart/form-data");response.setCharacterEncoding("utf-8");// 输出流到浏览器下载EasyExcel.write(out).needHead(true).head(tClass).excelType(ExcelTypeEnum.XLSX).autoCloseStream(true).registerWriteHandler(new ExcelHandler()).registerWriteHandler(ExcelHandler.getStyleStrategy()).sheet(0, "Sheet1").doWrite(dataList);}public static <T> List<T> importExcel(MultipartFile file, Class<T> tClass) {return importExcel(file, tClass, 1, null);}public static <T> List<T> importExcel(MultipartFile file, Class<T> tClass, String sheet) {return importExcel(file, tClass, 1, sheet);}public static <T> List<T> importExcel(MultipartFile file,Class<T> tClass,Integer headRowNumber,String sheet) {InputStream inputStream;try {inputStream = file.getInputStream();} catch (IOException e) {throw new RuntimeException(e);}List<T> list = null;list = EasyExcel.read(inputStream).registerConverter(new StringConverter()).registerReadListener(new ExcelValidateListener<T>()).head(tClass)// 可以指定sheet名字,不指定或null则表示第1个.sheet(sheet).headRowNumber(headRowNumber).doReadSync();list.removeIf(BeanHelper::allFieldAreNull);return list;}
}

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

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

相关文章

计算机体系结构作业2

1 P108 有一条动态多功能流水线由5段组成(如图3.35所示),加法用1、3、4、5段,乘法用1、2、5段,第2段的时间为2△t,其余各段的时间均为△t,而且流水线的输出可以直接返回输入端或暂存于相应的流水寄存器中。若在该流水线上计算 ∑ i 4 ( A i B i ) \sum_i^4(A_iB_i) ∑i4​(Ai…

python-leetcode 60.分割回文串

题目&#xff1a; 给定一个字符串S,请将S分割成一些子串&#xff0c;使每个子串都是回文串&#xff0c;返回S所有可能的分割方案 方法一&#xff1a;回溯深度优先搜索 1. 主要思想 使用 深度优先搜索&#xff08;DFS&#xff09; 遍历 s 的所有可能划分方式。使用 回溯&…

Java EE 进阶:MyBatis

MyBatis是一个优秀的持久化框架&#xff0c;用于简化JDBC的开发。 持久层就是持久化访问的层&#xff0c;就是数据访问层&#xff08;Dao&#xff09;&#xff0c;用于访问数据库的。 MyBatis使用的准备工作 创建项目&#xff0c;导入mybatis的启动依赖&#xff0c;mysql的驱…

Go语言的基础类型

一基础数据类型 一、布尔型&#xff08;Bool&#xff09; 定义&#xff1a;表示逻辑真 / 假&#xff0c;仅有两个值&#xff1a;true 和 false内存占用&#xff1a;1 字节使用场景&#xff1a;条件判断、逻辑运算 二、数值型&#xff08;Numeric&#xff09; 1. 整数类型&…

发布第四代液晶电视,TCL引领全新美学境界

在不断革新的消费电子领域中&#xff0c;电视行业在视觉体验上正面临重要的美学挑战。如何打破全面屏时代的物理束缚&#xff0c;将家居空间提升到“视觉无界”的层次&#xff0c;以及如何让尖端技术更好地服务于影像沉浸感&#xff0c;成为行业关注的焦点。 3月10日&#xff…

【C++】STL库面试常问点

STL库 什么是STL库 C标准模板库&#xff08;Standard Template Libiary&#xff09;基于泛型编程&#xff08;模板&#xff09;&#xff0c;实现常见的数据结构和算法&#xff0c;提升代码的复用性和效率。 STL库有哪些组件 STL库由以下组件构成&#xff1a; ● 容器&#xf…

【问题解决】Postman 测试报错 406

现象 Tomcat 日志 org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.logException Resolved org.springframework.web.HttpMediaTypeNotAcceptableException: No acceptable representation HTTP状态 406 - 不可接收 的报错&#xff0c;核心原因 客…

Flutter 打包 ipa出现错误问题 exportArchive

一、错误信息: Encountered error while creating the IPA: error: exportArchive: "Runner.app" requires a provisioning profile with the Push Notifications feature. Try distributing the app in Xcode: open /project/your_app/build/ios/archive/Runner.…

STC89C52单片机学习——第28节: [12-2] AT24C02数据存储秒表(定时器扫描按键数码管)

写这个文章是用来学习的,记录一下我的学习过程。希望我能一直坚持下去,我只是一个小白,只是想好好学习,我知道这会很难&#xff0c;但我还是想去做&#xff01; 本文写于&#xff1a;2025.03.20 51单片机学习——第28节: [12-2] AT24C02数据存储&秒表&#xff08;定时器扫…

Verilog-HDL/SystemVerilog/Bluespec SystemVerilog vscode 配置

下载 verible https://github.com/chipsalliance/verible的二进制包 然后配置 vscode

STM32使用HAL库,模拟UART输出字符串

测试芯片是STM32F103C8T6&#xff0c;直接封装好了&#xff0c;波特率是 9600 MyDbg.h #ifndef __MYDBG_H #define __MYDBG_H #include "stm32f1xx_hal.h" #include <stdio.h> #include <stdarg.h>/*使用GPIO口 模拟 UART 输出字符串 */ //初始化调试…

[工控机安全] 使用DriverView快速排查不可信第三方驱动(附详细图文教程)

导语&#xff1a; 在工业控制领域&#xff0c;设备驱动程序的安全性至关重要。第三方驱动可能存在兼容性问题、安全漏洞甚至恶意代码&#xff0c;威胁设备稳定运行。本文将手把手教你使用 DriverView工具&#xff0c;高效完成工控机驱动安全检查&#xff0c;精准识别可疑驱动&a…

洛谷P1434 [SHOI2002] 滑雪

P1434 [SHOI2002] 滑雪 - 洛谷 代码区&#xff1a; #include<algorithm> #include<iostream> #include<cstring> using namespace std;const int MAX 105; int r, c; int arr[MAX][MAX], dp[MAX][MAX]; int xindex[4] {-1,1,0,0};//上下左右 int yindex[…

【操作系统】进程间通信方式

进程间通信方式 前言 / 概述一、管道管道命名管道 二、消息队列三、共享内存四、信号量信号量概述互斥访问条件同步信号 五、socket总结 前言 / 概述 每个进程的用户地址空间都是独立的&#xff0c;⼀般而言是不能互相访问的&#xff0c;但内核空间是每个进程都共享的&#xff…

【程序人生】成功人生架构图(分层模型)

文章目录 ⭐前言⭐一、根基层——价值观与使命⭐二、支柱层——健康与能量⭐三、驱动层——学习与进化⭐四、网络层——关系系统⭐五、目标层——成就与财富⭐六、顶层——意义与传承⭐外层&#xff1a;调节环——平衡与抗风险⭐思维导图 标题详情作者JosieBook头衔CSDN博客专家…

【最后203篇系列】020 rocksdb agent

今天还是挺开心的一天&#xff0c;又在工具箱里加了一个工具。嗯&#xff0c;但是快下班的时候也碰到一些不太顺心的事&#xff0c;让我有点恼火。我还真没想到一个专职的前端&#xff0c;加测试&#xff0c;以及其他一堆人&#xff0c;竟然不知道后端返回的markdown,在前端渲染…

vulhub靶机----基于docker的初探索,环境搭建

环境搭建 首先就是搭建docker环境&#xff0c;这里暂且写一下 #在kali apt update apt install docker.io配置docker源&#xff0c;位置在/etc/docker/daemon.json {"registry-mirrors": ["https://5tqw56kt.mirror.aliyuncs.com","https://docker…

网络编程之解除udp判断客户端是否断开

思路&#xff1a;每几秒发送一条不显示的信息&#xff0c;客户端断开则不再发送信息&#xff0c;超时则表示客户端断开连接。&#xff08;心跳包&#xff09; 服务器 #include <head.h>#define MAX_CLIENTS 100 // 最大支持100个客户端 #define TIMEOUT 5 // 5秒…

B树与B+树在MySQL中的应用:索引

数据结构演示网站&#xff1a;Data Structure Visualization 先来了解两个数据结构B树与B树 B树&#xff1a; N阶B树每个节点最多存储N-1个Key&#xff0c;N个指针 例如&#xff1a;一个5阶B树&#xff0c;当前节点存储到5个Key时&#xff0c;中间的数会向上分离&#xff0c;…

Centos7配置本地yum源

Centos7配置本地yum源 1、基于iso镜像的centos源 1.1 准备iso <span style"color:#000000"><span style"background-color:#ffffff"><code class"language-bash"><span style"color:#008000"># 首先看自己使用…