使用easypoi读取Excel模板

1、只读取sheet0(只读取一个脚本号的Excel)

  • 前言:引入pom文件
  <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel-core</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.1.2</version>
        </dependency>

  • 读取文件模板
    在这里插入图片描述

  • 读取文件实体

//注意Excel 引入的包
//注意Excel 引入的包
//注意Excel 引入的包
import cn.afterturn.easypoi.excel.annotation.Excel;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestDto {
    @Excel(name = "姓名")
    private String name;
    @Excel(name = "年龄")
    private int age;
    @Excel(name = "性别")
    private String sex;
}
  • 读取文件
//controller层
public class ExcelImportController {
    @Autowired
    private ExcelImportServiceImpl excelImportService;

    @PostMapping("/import")
    @ApiOperation(value = "批量导入")
    public void importExcel() {
        File file = new File("D:\\maven_workplace\\Aproject-GJ\\yh-calculation-server\\calculation\\src\\main\\resources\\test.xlsx");
        return excelImportService.importExcel(file);
    }
}
//service层
@Service
public class ExcelImportServiceImpl {
    @Autowired
    private LossComputeService lossComputeService;


    public void importExcel(File file) {
        //文件进行校验
//        checkFile(file);
        //获取excel文件
        List<TestDto> excelImportCos = EasyExcelUtil.importExcel(file, TestDto.class);
        System.out.println("输出excel返回实体======>"+excelImportCos.toString());
        ArrayList<TestDto> testDtos = new ArrayList<>();
        for (TestDto testDto : excelImportCos) {
            TestDto dto = new TestDto();
            dto.setName(testDto.getName());
            dto.setAge(testDto.getAge());
            dto.setSex(testDto.getSex());
            testDtos.add(testDto);
        }
        System.out.println("输出封装到实体中的数据======>"+ testDtos.toString());
        return null;
    }
//EasyExcelUtil  工具类

@Component
@Slf4j
public class EasyExcelUtil {
    public static <T> List<T> importExcel(File file, Class<T> pojoClass)  {
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(1);
        params.setKeyIndex(1);
        return  importExcelExcep(file, pojoClass, params);
    }

    private static <T> List<T> importExcelExcep(File file, Class<T> pojoClass, ImportParams params) {
        List<T> list = null;
        try {
        //ExcelImportUtil  是包   cn.afterturn.easypoi.excel;
            list = ExcelImportUtil.importExcel(file, pojoClass, params);
//            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (Exception e) {
            log.error("导入失败",e);
            throw new RuntimeException("导入失败");
        }
        return list;
    }
}

结果:
在这里插入图片描述


2、读取多个脚本号的sheet…的Excel

  • 前言:引入pom文件
  <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel-core</artifactId>
            <version>3.3.2</version>
        </dependency>
        <dependency>
            <groupId>cn.afterturn</groupId>
            <artifactId>easypoi-base</artifactId>
            <version>4.1.2</version>
        </dependency>

  • 读取文件模板
    在这里插入图片描述
    在这里插入图片描述

  • 读取文件实体

//注意Excel 引入的包
//注意Excel 引入的包
//注意Excel 引入的包
import cn.afterturn.easypoi.excel.annotation.Excel;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestDto {
    @Excel(name = "姓名")
    private String name;
    @Excel(name = "年龄")
    private int age;
    @Excel(name = "性别")
    private String sex;
}
------------------------------------------------另一个实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Test2Dto {
    @Excel(name = "姓名")
    private String name;
    @Excel(name = "年龄")
    private int age;
    @Excel(name = "时间")
    private String time;
}
  • 读取文件
//controller层
public class ExcelImportController {
    @Autowired
    private ExcelImportServiceImpl excelImportService;

    @PostMapping("/import")
    @ApiOperation(value = "批量导入")
    public AjaxResult<LossCalculationLog> importExcel() {
        File file = new File("D:\\maven_workplace\\Aproject-GJ\\yh-calculation-server\\calculation\\src\\main\\resources\\test.xlsx");
        return excelImportService.importExcel(file);
    }
    }
    
//service层
@Service
public class ExcelImportServiceImpl {
    @Autowired
    private LossComputeService lossComputeService;


    public AjaxResult<LossCalculationLog> importExcel(File file) {
        //文件进行校验
//        checkFile(file);
        //获取所有字段名称
        String[] allIsExcelFields = EasyExcelUtil.getAllIsExcelFields(TestDto.class);
        System.out.println("获取的所有的字段名称"+allIsExcelFields.toString());
        //获取list字段sheet0
        List<TestDto> excelImportCos = EasyExcelUtil.importExcelBatch(file, 0, TestDto.class, allIsExcelFields);

        System.out.println("输出excel返回实体======>"+excelImportCos.toString());
        ArrayList<TestDto> testDtos = new ArrayList<>();
        for (TestDto testDto : excelImportCos) {
            TestDto dto = new TestDto();
            dto.setName(testDto.getName());
            dto.setAge(testDto.getAge());
            dto.setSex(testDto.getSex());
            testDtos.add(testDto);
        }
        System.out.println("输出sheet0 封装到实体中的数据======>"+ testDtos.toString());


        String[] allIsExcelFields1 = EasyExcelUtil.getAllIsExcelFields(Test2Dto.class);
        //获取list字段sheet0,
        List<Test2Dto> excelImportCos1 = EasyExcelUtil.importExcelBatch(file, 1, Test2Dto.class, allIsExcelFields1);
        System.out.println("输出excel返回实体======>"+excelImportCos1.toString());
        ArrayList<Test2Dto> testDtos1 = new ArrayList<>();
        for (Test2Dto testDto : excelImportCos1) {
            Test2Dto dto = new Test2Dto();
            dto.setName(testDto.getName());
            dto.setAge(testDto.getAge());
            dto.setTime(testDto.getTime());
            testDtos1.add(dto);
        }
        System.out.println("输出sheet1 封装到实体中的数据======>"+ testDtos1.toString());



        //封装请求体,并调用损失计算服务
return null;
    }
}

// EasyExcelUtil 工具

@Component
@Slf4j
public class EasyExcelUtil {
    public static <T> List<T> importExcel(File file, Class<T> pojoClass)  {
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(1);
        params.setKeyIndex(1);
        return  importExcelExcep(file, pojoClass, params);
    }

    private static <T> List<T> importExcelExcep(File file, Class<T> pojoClass, ImportParams params) {
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file, pojoClass, params);
//            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (Exception e) {
            log.error("导入失败",e);
            throw new RuntimeException("导入失败");
        }
        return list;
    }

    /**
     * EXCEL注解的字段
     * @param tClass
     * @return
     * @param <T>
     */
    public static<T> String[] getAllIsExcelFields(Class<T> tClass) {
        try{

            ArrayList<String> strings = new ArrayList<>();
            Field[] declaredFields = tClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                declaredField.setAccessible(true);
                if(declaredField.isAnnotationPresent(Excel.class)){
                    Excel annotation = declaredField.getAnnotation(Excel.class);
                    strings.add(annotation.name());
                }
            }
            String[] allIsExcelFields = strings.toArray(new String[strings.size()]);
            return allIsExcelFields;

        }catch (Exception e){
            log.error("获取所有标注了EXCEL注解的字段异常",e);
        }
        return null;
    }


    public static <T> List<T> importExcelBatch(File file, Integer sheetNun, Class<T> pojoClass, String[] templateFields) {
        ImportParams params = new ImportParams();
        params.setTitleRows(0);
        params.setHeadRows(1);
        //开始位置
        params.setStartSheetIndex(sheetNun);
        //数量
        params.setSheetNum(1);
        params.setImportFields(templateFields);
        return  importExcelExcep(file, pojoClass, params);
    }
}
//也可以进行文件校验-----写到service即可,或者抽取到一个工具类中
    private void checkFile(MultipartFile file) {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
        //上传文件为空 --异常,可自行定义
            throw new BizException(BizError.UPLOAD_FILE_EMPTY_ERROR.getMsg());
        }
        // 检查文件类型(支持 xlsx、xlsb、xlsm、xls、xlst)
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xlsb") && !fileName.endsWith(".xlsm") && !fileName.endsWith(".xls") && !fileName.endsWith(".xlst")) {
        //文件格式异常-----抛出异常可自行定义
            throw new BizException(BizError.IMP_IMPORT_FILE_TYPE_ERROR.getMsg());
        }
    }

结果:

在这里插入图片描述


使用Easypoi导出Excel模板时,如果需要在模板中添加签名图片,可以按照以下步骤进行配置: 1. 首先,确保你已经引入了Easypoi的相关依赖包,并在项目中进行了配置。 2. 创建一个Excel模板文件,可以使用Excel软件进行创建。在需要添加签名图片的位置,可以插入一个图片占位符,例如在单元格中插入一个文本“[img]”。 3. 在Java代码中,使用Easypoi提供的API来读取模板文件,并进行相应的配置。具体步骤如下: a. 创建一个Excel导出的实体类,用于存储导出数据的字段。 b. 使用`ExcelExportUtil`类的`exportExcel`方法来读取模板文件,并获取`Workbook`对象。 c. 使用`Workbook`对象的相关方法,如`getSheet`、`getRow`、`getCell`等,定位到需要添加签名图片的位置。 d. 使用Easypoi提供的`ImageEntity`类,创建一个图片实体对象,并设置图片的路径、宽度、高度等属性。 e. 使用`Workbook`对象的`addImage`方法,将图片实体对象添加到指定位置。 f. 最后,使用`ExcelExportUtil`类的`exportExcel`方法将修改后的Workbook对象导出为Excel文件。 4. 在导出Excel时,将实际的签名图片路径设置到图片实体对象中,以替换占位符。 下面是一个示例代码,演示了如何使用Easypoi导出带签名图片的Excel模板: ```java // 创建导出实体类 public class ExportEntity { // 其他字段... private String signatureImage; // 签名图片路径 // getter和setter方法... } // 导出Excel的方法 public void exportExcelWithSignature() { // 读取模板文件 Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ExportEntity.class, new ArrayList<>()); // 获取Sheet对象 Sheet sheet = workbook.getSheetAt(0); // 获取需要添加签名图片的位置 Row row = sheet.getRow(1); Cell cell = row.getCell(1); // 创建图片实体对象 ImageEntity imageEntity = new ImageEntity(); imageEntity.setUrl("path/to/signature.png"); // 设置签名图片路径 imageEntity.setWidth(100); // 设置图片宽度 imageEntity.setHeight(50); // 设置图片高度 // 添加图片到指定位置 sheet.addImage(imageEntity, cell); // 导出Excel文件 ExcelExportUtil.exportExcel(workbook, "output.xlsx"); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值