EasyExcel分页上传数据

EasyExcel分页上传数据

一、实例

  1. controller上传入口
 	@PostMapping("/upload")
    @ResponseBody
    @Log(title = "导入工单", businessType = BusinessType.IMPORT)
    public AjaxResult uploadFile(HttpServletRequest request, MultipartFile files) throws Exception {
        AjaxResult ajaxResult = this.checkFile(files);
        if (HttpStatus.SUCCESS != (int) ajaxResult.get(AjaxResult.CODE_TAG)) {
            return ajaxResult;
        }
        try {
            EasyExcel.read(files.getInputStream(), TWorkSheetReadVO.class, new WorkSheetListener(workSheetInnerService, new ArrayList<>())).sheet().doRead();
        } finally {
            //
        }
        return AjaxResult.success(String.format("上传成功"));
    }

	private AjaxResult checkFile(MultipartFile file) {
        String name = file.getOriginalFilename();
        String subName = name.substring(name.lastIndexOf('.'), name.length());
        if (!Lists.newArrayList(".xlsx", ".xls").contains(subName)) {
            return AjaxResult.error("只支持excel文件上传格式");
        }
        boolean checkSize = checkFileSize(file.getSize(), 10, "M");
        if(checkSize) return AjaxResult.success();
        return AjaxResult.error("上传的文件大小超过限制");
    }


    /**
     * 判断文件大小
     *
     * @param len  文件长度
     * @param size 限制大小
     * @param unit 限制单位(B,K,M,G)
     * @author youlu
     * @return
     */
    public static boolean checkFileSize(Long len, int size, String unit) {
		// long len = file.length();
        double fileSize = 0;
        if ("B".equals(unit.toUpperCase())) {
            fileSize = (double) len;
        } else if ("K".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1024;
        } else if ("M".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1048576;
        } else if ("G".equals(unit.toUpperCase())) {
            fileSize = (double) len / 1073741824;
        }
        if (fileSize > size) {
            return false;
        }
        return true;
    }
  1. 分页上传逻辑
package com.smy.ows.project.worksheet.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.smy.ows.project.worksheet.domain.vo.TWorkSheetReadVO;
import com.smy.ows.project.worksheet.service.inner.WorkSheetInnerService;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description
 * @ClassName ExcelModelListener
 * @Author youlu
 * @date 2023.02.02 15:01
 */
public class WorkSheetListener extends AnalysisEventListener<TWorkSheetReadVO> {

    private WorkSheetInnerService workSheetInnerService;
    private List<TWorkSheetReadVO> list;
    private static final int BATCH_COUNT = 1000;

    public WorkSheetListener(WorkSheetInnerService workSheetInnerService, List<TWorkSheetReadVO> list) {
        this.workSheetInnerService = workSheetInnerService;
        this.list = list;
    }


    @Override
    @Transactional
    public void invoke(TWorkSheetReadVO readVO, AnalysisContext analysisContext) {
        list.add(readVO);
        if (list.size() >= BATCH_COUNT) {
            workSheetInnerService.batchInsertWorkSheet(list);
            list.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    @Transactional
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //这里也要保存数据,确保最后遗留的数据也存储到数据库
        workSheetInnerService.batchInsertWorkSheet(list);
    }
}

  1. 插入数据库
@Override
    public void batchInsertWorkSheet(List<TWorkSheetReadVO> list) {
        workSheetService.batchInsert(list);
    }
  1. 实体对象
package com.smy.ows.project.worksheet.domain.vo;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.HeadStyle;
import com.alibaba.excel.converters.date.DateStringConverter;
import com.alibaba.excel.enums.poi.FillPatternTypeEnum;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.smy.framework.base.DesensitizationAnnotation;
import com.smy.ows.project.worksheet.enums.SheetLevelEnums;
import com.smy.ows.project.worksheet.enums.WorkSheetStatus;
import com.smy.ows.util.*;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;

/**
 * 客诉工单对象 t_work_sheet
 *
 * @author smy
 * @date 2023-01-11
 */
@Data
public class TWorkSheetReadVO implements Serializable {
    private static final long serialVersionUID = 5924360788178861972L;

    /**
     * 客诉标题
     */
    @ExcelProperty(value = "客诉标题", index = 0)
    @ColumnWidth(20)
    private String complaintHeadline;
    /**
     * @see SheetLevelEnums
     */
    @ExcelProperty(value = "优先级", index = 1, converter = PriorityIntegerStringConverter.class)
    @ColumnWidth(10)
    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
    private Integer priority;

    @ExcelProperty(value = "客户姓名", index = 2)
    @ColumnWidth(20)
    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
    private String custName;

    /**
     * 客户号
     */
    @ExcelProperty(value = "客户号", index = 3)
    @ColumnWidth(20)
    private String custNo;

    @DesensitizationAnnotation
    @ExcelProperty(value = "客户手机号", index = 4)
    @ColumnWidth(20)
    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
    private String custMobile;

    @DesensitizationAnnotation
    @ExcelProperty(value = "客户身份证", index = 5)
    @ColumnWidth(30)
    private String custIdNo;

    /**
     * 投诉时间
     */
    @ExcelProperty(value = "投诉时间(yyyy-MM-dd HH:mm:ss)", index = 6, converter = DateStringConverter.class)
    @ColumnWidth(40)
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date complaintTime;
    //反馈渠道
    @ExcelProperty(value = "反馈渠道", index = 7, converter = ChannelStringStringConverter.class)
    @ColumnWidth(15)
    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
    private String feedbackChannel;


    @ExcelProperty(value = "工单类型", index = 8, converter = TypeIntegerStringConverter.class)
    @ColumnWidth(15)
    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
    private Integer type;

    @ExcelProperty(value = "业务类型", index = 9, converter = BizTypeIntegerStringConverter.class)
    @ColumnWidth(15)
    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
    private Integer bizType;

    @DesensitizationAnnotation
    @ExcelProperty(value = "客户联系方式", index = 10)
    @ColumnWidth(15)
    private String custContactMobile;

    /**
     * 所属资方
     */
    @ExcelProperty(value = "所属资方", index = 11)
    @ColumnWidth(15)
    private String capital;

    @ExcelProperty(value = "投诉内容", index = 12)
    @ColumnWidth(30)
    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
    private String content;

    /**
     * @see WorkSheetStatus
     */
    @ExcelProperty(value = "工单状态", index = 13, converter = StatusIntegerStringConverter.class)
    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
    @ColumnWidth(15)
    private Integer status;

    @ExcelProperty(value = "处理结果", index = 14, converter = ResultIntegerStringConverter.class)
    @ColumnWidth(15)
    private Integer result;
    /**
     * 处理情况
     */
    @ExcelProperty(value = "处理情况", index = 15)
    @ColumnWidth(15)
    private String handingInfo;

}

其中要注意的是converter格式转换使用 。也可以自定义转换,将上传的数据转换成真正要接收的数据,例如:

	@ExcelProperty(value = "优先级", index = 1, converter = PriorityIntegerStringConverter.class)
    @ColumnWidth(10)
    @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40)
    private Integer priority;

这个属性是Integer 类型的。上传的数据如下是字符串类型的(一般,紧急,特急)。因此需要将其映射成数据库对应的integer数据。此时就需要自定义转换,在convertToJavaData方法中将字符串转换成相应的integer值。
在这里插入图片描述

package com.smy.ows.util;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.google.common.collect.Lists;
import com.smy.ows.common.core.domain.entity.SysDictData;
import com.smy.ows.common.utils.ParamThreadLocal;
import com.smy.ows.project.worksheet.constant.WorksheetDictTypeConstant;

import java.text.ParseException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class PriorityIntegerStringConverter implements Converter<Integer> {
    public PriorityIntegerStringConverter() {
    }

    public Class<?> supportJavaTypeKey() {
        return Integer.class;
    }

    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 读
     * @author youlu
     * @date 2023/8/18 10:46
     * @param cellData
     * @param contentProperty
     * @param globalConfiguration
     * @return java.lang.Integer
     */
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException {
        String priorityDesc = cellData.getStringValue();
        Map<String, List<SysDictData>> dictDataMap = (Map<String, List<SysDictData>>) ParamThreadLocal.getParam();
        Map<String, SysDictData> dataMap = Optional.ofNullable(dictDataMap.get(WorksheetDictTypeConstant.WORKSHEET_PRIORITY)).orElse(Lists.newArrayList()).stream()
                .collect(Collectors.toMap(k -> k.getDictLabel(), m -> m, (m1, m2) -> m2));
        SysDictData sysDictData = dataMap.get(priorityDesc);
        if (sysDictData == null) {
            return -1;
        }
        return Integer.valueOf(sysDictData.getDictValue());
    }

    /**
     * 写
     * @author youlu
     * @date 2023/8/18 10:46
     * @param value
     * @param contentProperty
     * @param globalConfiguration
     * @return com.alibaba.excel.metadata.data.WriteCellData<?>
     */
    public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        Map<String, List<SysDictData>> dictDataMap = (Map<String, List<SysDictData>>) ParamThreadLocal.getParam();
        Map<String, SysDictData> dataMap = Optional.ofNullable(dictDataMap.get(WorksheetDictTypeConstant.WORKSHEET_PRIORITY)).orElse(Lists.newArrayList()).stream()
                .collect(Collectors.toMap(k -> k.getDictValue(), m -> m, (m1, m2) -> m2));
        SysDictData sysDictData = dataMap.get(String.valueOf(value));
        if (sysDictData == null) {
            return new WriteCellData<String>("" + value);
        }
        return new WriteCellData<String>(sysDictData.getDictLabel());
    }
}

二、参考文档

easyExcel分页上传相应文档

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【cmu15445c++入门】(6)c++的迭代器

一、迭代器 C 迭代器是指向容器内元素的对象。它们可用于循环访问该容器的对象。我们知道迭代器的一个示例是指针。指针可用于循环访问 C 样式数组. 二、代码 自己实现一个迭代器 // C iterators are objects that point to an element inside a container. // They can be…

*s是什么意思

&s是地址&#xff0c;*是指针&#xff0c;*&s是指指向&s地址的指针&#xff1b; j *&s 就是 j s的意思。 例如&#xff1a;readRawData( (char *)& rowCount, sizeof(qint16)); //读取文本流中的行数到rowCount、列数到colCount qint16 rowCount, col…

BVH动画绑骨蒙皮并在Unity上展示

文章目录 Blender绑定骨骼Blender蒙皮Blender中导入bvh文件将FBX导入Unity Blender绑定骨骼 先左上角红框进入model模式&#xff0c;选中要绑定的模型&#xff0c;然后进入Edit模式把骨骼和关节对齐。 &#xff08;选中骨骼&#xff0c;G移动&#xff0c;R旋转&#xff09; 为…

如何进行游戏服务器的负载均衡和扩展性设计?

​在进行游戏服务器的负载均衡和扩展性设计时&#xff0c;需要考虑多个方面&#xff0c;以确保服务器的稳定性和可扩展性。以下是一些关键的步骤和考虑因素&#xff1a; 负载均衡的需求分析 在进行负载均衡设计之前&#xff0c;需要深入了解游戏服务器的负载特性和需求。这包括…

牛客“迎新春,过大年”多校程序设计竞赛A题

题目描述&#xff1a; 这里有个小trick 当时也看到数据范围的问题了 n 是 1 e 6 ∑ i 1 n a [ i ] < 5 e 7 n是1e6 \quad \sum_{i1}^na[i]<5e7 n是1e6∑i1n​a[i]<5e7 我们考虑不同的数 1 2 . . . k − 1 k 1 \quad 2 \quad ... k-1 \quad k 12...k−1k s u m …

ChatGPT论文指南|ChatGPT论文写作过程中6个润色与查重提示词

论文完成初稿之后&#xff0c;一般情况下&#xff0c;宝子们还需要找专家给我们提出评审意见。找专家评审其实并不容易&#xff0c;即使对老师来说&#xff0c;找人评审论文也是一件苦活。我们这个时候可以通过文字提示让 ChatGPT充当我们的评审专家&#xff0c;为论文提出问题…

车位检测,YOLOV8,OPENCV调用

车位检测YOLOV8NANO,opencv调用 车位检测&#xff0c;YOLOV8NANO&#xff0c;训练得到PT模型&#xff0c;然后转换成ONNX&#xff0c;OPENCV的DNN调用&#xff0c;支持C,PYTHON,ANDROID

macbookpro和macbookair的区别?cleanmymac 怎么清理mac空间

苹果mac air和pro区别有&#xff1a;1、air采用了轻薄的设计&#xff0c;重量相对较轻&#xff0c;便于携带&#xff0c;而pro更加注重性能&#xff0c;所以比较重&#xff1b;2、air通常搭载较低功耗的处理器内存和存储容量相对较小&#xff0c;而pro配备了更强大的处理器、更…

HarmonyOS 鸿蒙应用开发(九、还是蓝海,如何贡献第三方库)

快来共享第三方库吧&#xff0c;不但可以通过分享自己的成果&#xff0c;可以获得来自全球开发者的技术反馈和建议&#xff0c;提升自身技术能力&#xff0c;还有助于提高个人或团队在开源社区中的知名度和影响力。在流量时代和粉丝经济时代&#xff0c;获得曝光度和流量密码。…

HarmonyOS鸿蒙ArkTS证件照生成模板(适合二次开发,全套源码版)

预览效果 部分代码 开发语言 HarmonyOS 鸿蒙 ArkTS语言 &#xff08;Stage模型&#xff09; 备注 一键生成&#xff0c;自带证件照数集&#xff0c; 为开发者带来二次开发和学习体验&#xff0c; 在这祝福开发者们使用愉快。 使用方法 下载后通过DevEco Studio开发工…

腾讯云游戏服务器配置有哪些?

2024年更新腾讯云游戏联机服务器配置价格表&#xff0c;可用于搭建幻兽帕鲁、雾锁王国等游戏服务器&#xff0c;游戏服务器配置可选4核16G12M、8核32G22M、4核32G10M、16核64G35M、4核16G14M等配置&#xff0c;可以选择轻量应用服务器和云服务器CVM内存型MA3或标准型SA2实例&am…

软考21-上午题-数组、矩阵

数组&#xff1a;一组地址连续的空间。 数组是定长线性表在维数上的扩展&#xff0c;即&#xff0c;线性表中的元素又是一个线性表。 一、数组 数组的特点&#xff1a; 数组数目固定&#xff0c;一旦定义了数组结构&#xff0c;不再有元素个数的增减变化。因此&#xff0c;数…

寒假作业-day4

1>请编程实现哈希表的创建存储数组{12,24,234,234,23,234,23}&#xff0c;输入key查找的值&#xff0c;实现查找功能。 代码&#xff1a; #include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> typedef int datatype; type…

解决Python xlwings报错AttributeError ‘NoneType‘ object has no attribute apps

一、问题背景 今天&#xff0c;遇到了一个问题&#xff1a;以前调试好的python使用xlwings操作wps表格的脚本突然不能运行了&#xff0c;遇到了很多莫名问题&#xff0c;下面记录分享下&#xff1a; 开始报错如下&#xff1a; D:\PycharmProjects\tiku\venv\Scripts\python.e…

【制作100个unity游戏之23】实现类似七日杀、森林一样的生存游戏11(附项目源码)

本节最终效果演示 文章目录 本节最终效果演示系列目录前言选中效果 快捷栏显示对应的手臂工具源码完结 系列目录 前言 欢迎来到【制作100个Unity游戏】系列&#xff01;本系列将引导您一步步学习如何使用Unity开发各种类型的游戏。在这第23篇中&#xff0c;我们将探索如何制作…

深度学习缝模块怎么描述创新点?(附写作模板+涨点论文)

深度学习缝了别的模块怎么描述创新点、怎么讲故事写成一篇优质论文&#xff1f; 简单框架&#xff1a;描述自己这个领域&#xff0c;该领域出现了什么问题&#xff0c;你用了什么方法解决&#xff0c;你的方法有了多大的性能提升。 其中&#xff0c;重点讲清楚这两点&#xf…

【Qt Design】界面介绍

文章目录 前言Widget Box&#xff08;工具箱&#xff09;对象查看器Qt Design属性编译器sizePolicy内容 信号/槽编辑器资源浏览器ui文件 前言 Widget Box&#xff08;工具箱&#xff09; 提供很多控件 对象查看器 对象查看区域&#xff0c;可以查看主窗口放置对象的列表 …

力扣面试题 05.03. 翻转数位(前、后缀和)

Problem: 面试题 05.03. 翻转数位 文章目录 题目描述思路及解法复杂度Code 题目描述 思路及解法 1.将十进制数转换为二进制数&#xff08;每次按位与1求与&#xff0c;并且右移&#xff09;&#xff1b; 2.依次求取二进制数中每一位的前缀1的数量和&#xff0c;和后缀1的数量和…

MongoDB的操作和理解

什么是MongoDB? MongoDB&#xff1a;基于分布式文件存储的数据库由C语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB是一个介于关系数据库和非关系数据库(nosql)之间的产品&#xff0c;是非关系数据库当中功能最丰富&#xff0c;最像关系数据库的。 Mo…

Webshell一句话木马

一、webshell介绍&#xff08;网页木马&#xff09; 分类&#xff1a; 大马&#xff1a;体积大、隐蔽性差、功能多 小马&#xff1a;体积小&#xff0c;隐蔽强&#xff0c;功能少 一句话木马&#xff1a;代码简短&#xff0c;灵活多样 二、一句话木马&#xff1a; &#xff1a;…
最新文章