报错原因

由于easyexcel导入导出时如果存在null会报错,跟踪源码com.alibaba.excel.analysis.v07.XlsxSaxAnalyser#parseXmlSource,查看xmlReader.parse,发现这里try了没啥卵用,第一次启动导入或者导出时,有null值一样报错。因为excel有空值,不能直接用,所以我自定义了一个excel的导入导出

自定义excel导入导出

导入pom依赖,easyexcel包含了apache.poi的依赖

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

自定义注解ExcelColumn 用来处理excel的导入导出:

package com.xxx.core.anno;
import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;import java.lang.annotation.*;/*** excel导出表格注解** @author :seagull* @date :Created in 2022/7/12* @description:* @modified By:*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelColumn {String name() default "";@AliasFor("name")String value() default "";}

一个model类,使用自定义注解提供表格标题信息

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@TableName("sys_dictionary")
public class Dictionary implements Serializable {/*** ID*/@TableId(value = "id", type = IdType.AUTO)@ExcelColumn("ID")private Integer id;/*** 字典名称*/@TableField(value = "name")@ExcelColumn("字典名称")private String name;/*** 父id*/@TableField(value = "pid")@ExcelColumn("父id")private Integer pid;/*** 排序*/@TableField(value = "num")@ExcelColumn("排序")private Integer num;/*** 提示*/@TableField(value = "tips")@ExcelColumn("提示")private String tips;@TableField(exist = false)private List<Dictionary> dictionaryList;}

创建一个excel工具类

package com.xxx.core.utils;import com.xxx.core.anno.ExcelColumn;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;/*** excel工具类** @author :seagull* @date :Created in 2022/7/12* @description:* @modified By:*/
public class ExcelUtil {/*** 导入excel** @param file* @param <T>* @return*/public static <T> List<T> importExcel(MultipartFile file, Class<?> clazz) throws IOException, InstantiationException, IllegalAccessException, ParseException {List<T> list = new ArrayList<>();XSSFWorkbook sheets = new XSSFWorkbook(file.getInputStream());//读取文件//获取sheetXSSFSheet sheet = sheets.getSheetAt(0);XSSFRow firstRow = sheet.getRow(0);int firstRowLength = firstRow.getPhysicalNumberOfCells();/*首行名称列表*/List<String> firstRowCellList = new ArrayList<>();for (int i = 0; i < firstRowLength; i++) {String firstRowCellValue = firstRow.getCell(i).toString();firstRowCellList.add(firstRowCellValue);}//获取行数int rows = sheet.getPhysicalNumberOfRows();for (int i = 1; i < rows; i++) {//获取列数XSSFRow row = sheet.getRow(i);int columns = row.getPhysicalNumberOfCells();Field[] fields = clazz.getDeclaredFields();Object newInstance = clazz.newInstance();for (int j = 0; j < firstRowCellList.size(); j++) {String titleCellValue = firstRowCellList.get(j);/*根据行单元格名称获取带有指定注解的字段*/Field field = getCustomField(fields, titleCellValue);if (field == null) {continue;}XSSFCell cell = row.getCell(j);if (cell == null) {continue;}String cellValue = cell.toString();field.setAccessible(true);switch (field.getType().getName()) {case "java.lang.Integer":Integer num = 0;try {num = Integer.parseInt(cellValue.substring(0, cellValue.contains(".") ? cellValue.indexOf(".") : cellValue.length()));} catch (NumberFormatException e) {e.printStackTrace();}field.set(newInstance, num);break;case "java.lang.String":field.set(newInstance, cellValue);break;case "java.util.Date":field.set(newInstance, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(cellValue));break;}System.out.print(cellValue + "   ");}System.out.println();list.add((T) newInstance);}return list;}/*** 根据行单元格名称获取带有指定注解的字段** @param fields* @param cellName* @return*/private static Field getCustomField(Field[] fields, String cellName) {for (int i = 0; i < fields.length; i++) {ExcelColumn annotation = fields[i].getAnnotation(ExcelColumn.class);if (annotation != null) {if (cellName.equals(annotation.value())) {return fields[i];}}}return null;}/*** 直接将数据写到客户端** @param response* @param dataList* @param clazz* @param <T>* @throws Exception*/public static <T> void exportExcel(HttpServletResponse response, List<T> dataList, Class<T> clazz) throws Exception {Field[] fields = clazz.getDeclaredFields();Map<String, Object> filedMap = new LinkedHashMap<>();for (Field field : fields) {Class<?> type = field.getType();ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);if (annotation != null) {filedMap.put(field.getName(), annotation.value());}}XSSFWorkbook workbook = new XSSFWorkbook();//创建行String[] columnNames = filedMap.values().toArray(new String[0]);Sheet sheet = workbook.createSheet();Font titleFont = workbook.createFont();titleFont.setFontName("simsun");titleFont.setBold(true);titleFont.setColor(IndexedColors.BLACK.index);XSSFCellStyle titleStyle = workbook.createCellStyle();titleStyle.setAlignment(HorizontalAlignment.CENTER);titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);titleStyle.setFillForegroundColor(IndexedColors.YELLOW.index);titleStyle.setFont(titleFont);Row titleRow = sheet.createRow(0);for (int i = 0; i < columnNames.length; i++) {Cell cell = titleRow.createCell(i);cell.setCellValue(columnNames[i]);cell.setCellStyle(titleStyle);}//创建数据行并写入值for (T obj : dataList) {int lastRowNum = sheet.getLastRowNum();Row dataRow = sheet.createRow(lastRowNum + 1);int index = 0;for (String filedName : filedMap.keySet()) {String fieldTypeName = filedMap.get(filedName).toString();Class<?> aClass = obj.getClass();Field field = aClass.getDeclaredField(filedName);field.setAccessible(true);Object value = field.get(obj);dataRow.createCell(index++).setCellValue(value == null ? null : value.toString());}}response.setContentType("application/vnd.ms-excel");response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("easyexcel.xlsx", "utf-8"));response.setHeader("Access-Control-Expose-Headers", "content-Disposition");OutputStream outputStream = response.getOutputStream();workbook.write(outputStream);outputStream.flush();outputStream.close();}}

使用方式


@Testpublic void testExcel() {List<A> list = ExcelUtil.importExcel(file, A.class);//假如传了file// 导出用js创建a标签下载ExcelUtil.exportExcel(response, list, A.class);}

easyexcel 第一次导入导出会报错com.alibaba.excel.exception.ExcelAnalysisException,所以自定义excel导入导出表格相关推荐

  1. EasyExcel导入的时候报错Caused by: java.lang.NoClassDefFoundError: org/apache/poi/poifs/filesystem/File

    今天用EasyExcel导入的时候报错,如下 com.alibaba.excel.exception.ExcelAnalysisException: java.lang.NoClassDefFound ...

  2. SAP LSMW 导入物料主数据报错 - You have not fully maintained the descriptions - 之分析

    SAP LSMW 导入物料主数据报错 - You have not fully maintained the descriptions - 之分析 近日,笔者忙于在D项目上的主数据导入.这是D项目上的 ...

  3. android项目模块导入eclipse编译报错,android中studio导入eclipse项目报错怎么办

    android中studio导入eclipse项目报错怎么办 发布时间:2020-07-15 17:34:45 来源:亿速云 阅读:96 作者:清晨 这篇文章将为大家详细讲解有关android中stu ...

  4. oracle解决00302,oracle 导入数据,报错PLS-00302: component 'SET_NO_OUTLINES' must be declared...

    oracle 导入数据,报错PLS-00302: component 'SET_NO_OUTLINES' must be declared . 今天将本机的一个导出的库,导入到中一个oracle数据库 ...

  5. Open3D o3dtut怎么导入才不报错

    Open3D o3dtut 怎么导入才不报错 问题 解决 1. 导入o3dtut 2. 添加open3d_tutorial.py类 3. 构建目录结构 4. 运行成功 写这篇博客源于博友的提问,最初我 ...

  6. python3.7导入gevent模块报错的解决方案

    python3.7导入gevent模块报错的解决方案 参考文章: (1)python3.7导入gevent模块报错的解决方案 (2)http://www.cnblogs.com/eva-j/p/939 ...

  7. java项目导入包报错_转!java web项目 build path 导入jar包,tomcat启动报错 找不到该类...

    在eclipse集成tomcat开发java web项目时,引入的外部jar包,编译通过,但启动tomcat运行web时提示找不到jar包内的类,需要作如下配置,将jar包在部署到集成的tomcat环 ...

  8. 往sde中导入要素类报错000732

    sde可以成功连接,可以在Server中注册. 但是向sde中导入要素类报错000732,如图所示. 点击红色圆圈提示 ERROR 000732. 将路径修改为绝对路径即可,如下图所示. 转载于:ht ...

  9. Oracle导入TYPE对象报错ORA-02304

    Oracle导入TYPE对象报错ORA-02304 Type是我们经常使用的数据库对象结构.我们在实际中,可以单独定义type类型,之后在PL/SQL代码或者数据表中使用. 在一个偶然的机会让笔者发现 ...

  10. eclipse项目导入到AndroidStudioc报错

    eclipse项目导入到AndroidStudioc报错 Error:java.util.concurrent.ExecutionException: com.android.ide.common.p ...

最新文章

  1. K8S Learning(10)——Pod配置
  2. “数据资产化探索”专题
  3. 只靠自己的飞鸽传书想象和推断
  4. oracle ora 01152,ORA-01152 故障解决
  5. mysql geometry 附近的人_mysql中geometry类型的简单使用(搜索附近的人)
  6. 重庆三峡学院计算机英语期末考试,英语语言学试题B卷及答案(重庆三峡学院)
  7. 启程 一些高考后的想法
  8. 基础知识的困惑让BUG更隐蔽
  9. java bigInteger +1 加常数
  10. IntelliJ IDEA使用教程 (总目录篇)
  11. FFmpeg合并ts文件为mp4文件
  12. “秃“如其来的植发经济是一门好生意吗?
  13. android 路由表命令,一个轻量简易的Android路由框架
  14. 类似于萝卜书摘的书摘app推荐
  15. 万豪国际集团推出“双十一”多样化旅行套餐产品
  16. 分别计算二维数组主对角线元素与辅对角线元素的和。
  17. 深入浅出JS—03 函数闭包和内存泄漏
  18. 微信小程序 数据在缓存中的存储和获取
  19. error C2248: “CObject::CObject”: 无法访问private 成员(在“CObject”类中声明)
  20. Matlab:利用Matlab软件进行GUI界面设计实现图像的基本操作

热门文章

  1. 汉字转拼音(汉语拼音)util
  2. 2-10配置Linux网络
  3. 注意ITUNES与ECLIPSE,TOMCAT冲突
  4. 【Python/Pytorch - Bug】-- RuntimeError: ,expected input[16,12,174,145] to have 8 channels,but got 12
  5. POP3、SMTP和IMAP 协议
  6. oracle ap tp是什么,AP模式和Router模式区别是什么
  7. win7一点计算机就卡死,win7系统电脑经常卡住假死页面关不掉的解决方法
  8. pgMP认证,还是再看看吧!
  9. 好豆直播功能需求分析与优先级排序
  10. 【渝粤题库】陕西师范大学151113 财经法规与职业道德