easyexcel导入导出+动态列+自定义样式

文章详细介绍了如何使用EasyExcel库来处理Excel文件,包括引入Maven依赖,使用模板文件,展示导出和导入的效果,并提供了一个自定义的EasyWriteHandler来处理单元格、行和工作簿。此外,还展示了测试工具类ExcelTest中的导出和上传功能,利用JavaFaker生成测试数据,并应用了样式策略来格式化内容。
摘要由CSDN通过智能技术生成

目录

1、引用maven依赖

2、模板文件template1.xlsx

3、导出效果

4、导入效果

5、导出用EasyWriteHandler

6、测试工具类 ExcelTest


1、引用maven依赖

<!-- easyexcel -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>easyexcel</artifactId>
    <version>3.2.1</version>
</dependency>
<!-- java 造数据用 -->
<dependency>
    <groupId>com.github.javafaker</groupId>
    <artifactId>javafaker</artifactId>
    <version>0.17.2</version>
</dependency>

2、模板文件template1.xlsx

e4d0f7888a784deeaf6d94e7c516d03a.png

3、导出效果

845635c4c53c4f32bd975de9726e1cbc.png

4、导入效果

99c2dd588d2549d1a669a8ced7bc2ba0.png

5、导出用EasyWriteHandler


import com.alibaba.excel.util.WorkBookUtil;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.WorkbookWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

public class EasyWriteHandler implements WorkbookWriteHandler, SheetWriteHandler, RowWriteHandler, CellWriteHandler {

    private Integer startRowIndex;
    private Integer lastColumnIndex;



    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
                                Integer relativeRowIndex, Boolean isHead) {
        if(startRowIndex == null){
            startRowIndex = row.getRowNum();
            lastColumnIndex = Integer.valueOf(row.getLastCellNum());
        }
    }

    public EasyWriteHandler(){}
    public Cell cell(Sheet sheet ,int rowIndex,int cellIndex){
        Row row = sheet.getRow(rowIndex);
        if (row == null) {
            row = WorkBookUtil.createRow(sheet, rowIndex);
        }
        Cell cell = row.getCell(cellIndex);
        if (cell == null) {
            cell = WorkBookUtil.createCell(row, cellIndex);
        }
        return cell;
    }

    public Integer getStartRowIndex() {
        return startRowIndex;
    }

    public Integer getLastColumnIndex() {
        return lastColumnIndex;
    }
}

6、测试工具类 ExcelTest


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.handler.context.WorkbookWriteHandlerContext;
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.fastjson.JSON;
import com.github.javafaker.Faker;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Sheet;
import org.junit.Test;
import xiao.utils.FakerUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;


public class ExcelTest {
    @Test
    public void testExport() throws Exception {
        String fileName = "D:/export.xlsx";
        String templateFile = "D:/template1.xlsx";

        List<List<String>> headList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            List<String> head = new ArrayList<>();
            head.add("code"+i);
            head.add("标题"+i);
            headList.add(head);
        }

        Faker faker = FakerUtil.FAKER;
        List<List<String>> dataList = Stream.generate(() -> {
            List<String> data=new ArrayList<>();
            for (int i = 0; i < 10; i++) {
                data.add(faker.name().fullName());
            }
            return data;
        }).limit(50).collect(Collectors.toList());


        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short)14);
        headWriteCellStyle.setWriteFont(headWriteFont);
        //内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
        WriteFont contentWriteFont = new WriteFont();
        contentWriteFont.setFontHeightInPoints((short)10);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);


        WriteCellStyle headBlueWriteCellStyle=new WriteCellStyle();
        headBlueWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());


        //添加自定义样式和修改固定单元格内容时需要加上 .inMemory(true)
        EasyExcel.write(fileName)
                .withTemplate(templateFile).head(headList).inMemory(true)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(new EasyWriteHandler() {
                    @Override
                    public void afterCellDispose(CellWriteHandlerContext context) {
                        if (context.getHead()) {
                            Cell cell = context.getCell();
                            if(cell.getColumnIndex()%2 == 0){
                                WriteCellStyle.merge(headBlueWriteCellStyle,
                                        context.getFirstCellData().getOrCreateStyle());
                            }
                        }
                    }

                    @Override
                    public void afterWorkbookDispose(WorkbookWriteHandlerContext context) {
                        Sheet sheet = context.getWriteContext().writeSheetHolder().getSheet();
                        for (int columnIndex = 0; columnIndex < getLastColumnIndex() ; columnIndex++) {
                            //设置自适应列宽
                            sheet.autoSizeColumn(columnIndex);
                        }
                        //设置部门名称
                        cell(sheet,1,1).setCellValue("开发部门");

                    }
                }).sheet().doWrite(dataList);
    }
    @Test
    public void testUpload() throws Exception {
        String fileName = "D:/export.xlsx";
        List<Map<Integer, String>> resultList = EasyExcel.read(fileName).sheet().headRowNumber(2).doReadSync();
        System.out.println(JSON.toJSON(resultList));
    }
}

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
easyexcel可以实现导入动态的功能。你可以使用以下步骤来实现: 1. 引入easyexcel的maven依赖,确保在你的项目中有以下依赖: ``` <!-- easyexcel --> <dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>3.2.1</version> </dependency> ``` 2. 准备一个模板文件,比如template1.xlsx,模板文件中的可以根据需求动态生成。 3. 编写代码实现导入动态的功能。你可以使用以下代码作为参考: ``` @Test public void test1() throws FileNotFoundException, IllegalAccessException, InstantiationException { // 读取Excel文件并导入动态 List<A> as = Excels.importsDynamic(new FileInputStream(new File("C:\\Users\\caobinghui\\Desktop\\test.xlsx")), A.class); // 打印导入的数据 as.forEach(System.out::println); } ``` 这样,你就可以使用easyexcel导入动态了。请确保你的模板文件中的导入对象的属性匹配。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [EasyExcel支持导入动态](https://blog.csdn.net/weixin_44204191/article/details/124561932)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* [easyexcel导入导出+动态+自定义样式](https://blog.csdn.net/qq_34783476/article/details/130364172)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值