Excel导入功能接口

一、通过easyexcel实现数据导入

1、简单实现数据导入

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.SyncReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.meirit.dong.excel.entity.ProductImportEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author dxj
 * @since 2022-12-14 11:15
 */
@Service
public class ImportExceltService {
    public List<ProductImportEntity> importExcel(MultipartFile multipartFile) throws IOException {
        SyncReadListener syncReadListener = new SyncReadListener();
        EasyExcel.read(multipartFile.getInputStream(), ProductImportEntity.class, syncReadListener).sheet().doRead();
        List<Object> list = syncReadListener.getList();
        List<ProductImportEntity> products = JSONArray.parseArray(JSON.toJSONString(list), ProductImportEntity.class);
        return products;
    }
}

2、具备信息验证功能的Excel导入

   1)导入实体类

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import lombok.Data;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;

/**
 * @author dxj
 * @since 2022-12-14 13:48
 */
@Data
public class ProductImportEntity {
    @ExcelProperty(value = {"姓名"},order = 1)
    @ColumnWidth(value = 20)
    @Length(message = "姓名长度超过限制长度",max = 20)
    @NotNull(message = "姓名不能为空")
    private String name;

    @ExcelProperty(value = {"类型"},order = 2)
    @ColumnWidth(value = 20)
    @Length(message = "类型长度超过限制长度",max = 20)
    @NotNull(message = "类型不能为空")
    private String type;

    @ExcelProperty(value = {"价格"},order = 3)
    @ColumnWidth(value = 20)
    @Max(message = "价格大小超过限制",value = 9999)
    private Long price;

    @ExcelProperty(value = {"地址"},order = 4)
    @ColumnWidth(value = 40)
    @Length(message = "地址长度超过限制长度",max = 1000)
    private String address;

    @ExcelIgnore
    private String description;
}
@ExcelProperty中的value就是表头字段值,index指的是具体Excel的列数,从1开始@ColumnWidth 是定义列宽
@Length 注解,message用来提示信息,max为导入值限制
@NotNull 注解,非空校验

 2)导入监听类

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.google.common.collect.Maps;
import com.meirit.dong.excel.entity.ImportExcelModel;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

/**
 * excel导入监听
 *
 * @author dongxiajun
 * @since 2022-12-16 17:40
 */
@Data
@NoArgsConstructor
public class EasyExcelListener<T extends ImportExcelModel> extends AnalysisEventListener<T> {
    private static final String ERROR_TIP = "第%d行,第%d列类型有误";
    List<T> list = Lists.newArrayList();
    List<T> failList = Lists.newArrayList();
    boolean isSuccess = false;
    Class aClass;

    public EasyExcelListener(Class aClass) {
        super();
        this.aClass = aClass;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        t.setRowNum(analysisContext.readRowHolder().getRowIndex());
        list.add(t);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        isSuccess = true;
    }

    /**
     * 异常处理
     *
     * @param exception exception
     * @param context   context
     * @throws Exception Exception
     */
    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        isSuccess = false;
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            ImportExcelModel importExcelModel = new ImportExcelModel();
            importExcelModel.setRowNum(context.readRowHolder().getRowIndex());
            importExcelModel.setErrorMsg(String.format(ERROR_TIP, excelDataConvertException.getRowIndex() + 1, excelDataConvertException.getColumnIndex() + 1));
        }
        super.onException(exception, context);
    }

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        super.invokeHead(headMap, context);
        try {
            Map<Integer, String> excelHeadMap = getExcelHeadMap();
            for (Integer key : headMap.keySet()) {
                String value = headMap.get(key).getStringValue();
                if (StringUtils.isEmpty(value) || !StringUtils.equals(value, excelHeadMap.get(key))) {
                    throw new ExcelAnalysisException("excel 表头有误");
                }
            }
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public Map<Integer, String> getExcelHeadMap() throws NoSuchFieldException {
        Field[] fields = aClass.getDeclaredFields();
        Map<Integer, String> excelHeadMap = Maps.newTreeMap();
        for (int i = 0; i < fields.length; ++i) {
            Field field = aClass.getDeclaredField(fields[i].getName());
            ReflectionUtils.makeAccessible(field);
            ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
            if (excelProperty != null) {
                int order = excelProperty.order();
                String[] values = excelProperty.value();
                excelHeadMap.put(order, String.join("", values));
            }
        }
        return excelHeadMap;
    }

}

3)业务逻辑处理

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要实现Java配合Element实现Excel导入功能,可以按照以下步骤进行操作: 1. 添加Element依赖:在你的Java项目中,首先需要添加Element的相关依赖。你可以在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.webjars.npm</groupId> <artifactId>element-ui</artifactId> <version>2.15.1</version> </dependency> ``` 或者你也可以直接下载Element的压缩包,将其中的CSS和JS文件引入到你的项目中。 2. 创建上传组件:使用Element提供的上传组件,用于选择并上传Excel文件。你可以在HTML文件中添加以下代码: ```html <el-upload :action="uploadUrl" :file-list="fileList" :on-change="handleUpload"> <el-button slot="trigger" size="small" type="primary">选择文件</el-button> <el-button style="margin-left: 10px;" size="small" type="success" @click="handleImport">导入</el-button> </el-upload> ``` 其中,`uploadUrl` 是上传文件的后端接口地址,`fileList` 是存放已选择文件的数组。`handleUpload` 方法用于监听文件选择事件,`handleImport` 方法用于执行导入操作。 3. 后端处理:在后端使用Java代码处理上传的Excel文件。你可以使用Apache POI库来读取Excel文件内容。以下是一个简单的示例代码: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try (InputStream inputStream = file.getInputStream()) { Workbook workbook = WorkbookFactory.create(inputStream); Sheet sheet = workbook.getSheetAt(0); // 遍历行 for (Row row : sheet) { // 遍历单元格 for (Cell cell : row) { // 处理单元格数据 String value = cell.toString(); System.out.print(value + "\t"); } System.out.println(); } return "success"; } catch (IOException | EncryptedDocumentException | InvalidFormatException e) { e.printStackTrace(); return "error"; } } ``` 在这个示例中,我们使用`WorkbookFactory`来创建Workbook对象,然后获取第一个Sheet,并遍历行和单元格来处理数据。你可以根据实际需求进行更详细的处理。 这样,你就可以使用Java配合Element实现Excel导入功能了。记得在前端页面中调用后端的上传接口,并根据需要对Excel数据进行进一步处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值