当前位置: 首页 > article >正文

Java基于easyExcel的自定义表格格式

这里用的到easyExcel版本为3.3.4

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

效果

代码部分

package com.tianyu.test;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.write.style.ContentLoopMerge;
import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import lombok.Data;
import org.apache.commons.compress.utils.Lists;
import org.apache.poi.ss.formula.functions.Count;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.junit.Test;


import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


public class test{


    private String filePath="src/main/resources/file/";

    @Test
    public void exportExcel(){
        String filePath = this.filePath+ File.separator + "exportExcel"+System.currentTimeMillis() + ".xlsx";

        EasyExcel.write(filePath)
                .head(this.getHead())       						// 表格标题
                .sheet("测试")    										// sheet页名称
                .registerWriteHandler(setCellStyle())		// 样式
                .registerWriteHandler(new CustomMergeStrategy(7, 7, 1,3)) // 合并第8行的2到4列,即合并旁边的B8:D8

                .doWrite(this.getData());	   // 数据

    }

    /**
     * 表格标题
     * @return
     */
    private static List<List<String>> getHead(){
        List<List<String>> head = new ArrayList<>();
        List l1=Lists.newArrayList();
        l1.add("合并");
        l1.add("序号");

        List l2=Lists.newArrayList();
        l2.add("合并");
        l2.add("年龄");

        List l3=Lists.newArrayList();
        l3.add("合并");
        l3.add("姓名");

        List l4=Lists.newArrayList();
        l4.add("换行");

        head.add(l1);
        head.add(l2);
        head.add(l3);
        head.add(l4);
        return head;
    }

    /**
     * 导出数据
     * @return
     */

    private static List<List<Object>> getData(){
        List<List<Object>> dataList = new ArrayList<List<Object>>();
        for (int i = 1; i < 6; i++) {
            List<Object> data = new ArrayList<>();
            data.add(i);
            data.add("名称"+i);
            data.add(i+10);
            data.add("测试自动换行"+i);
            dataList.add(data);
        }
        List<Object> countCol=new ArrayList<>();
        countCol.add("合计");
        countCol.add("");
        countCol.add("");
        countCol.add("");
        dataList.add(countCol);
        return dataList;
    }




    /**
     * 表格样式
     * @return
     */
    private static HorizontalCellStyleStrategy setCellStyle() {

        // 表格标题样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 设置标题居中对齐
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 设置标题颜色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        // 标题字体
        WriteFont headFont = new WriteFont();
        // 设置标题字体大小
        headFont.setFontHeightInPoints((short) 12);
        headWriteCellStyle.setWriteFont(headFont);
        headFont.setColor(IndexedColors.BLACK.getIndex());
        //设置自动换行
        headWriteCellStyle.setWrapped(true);


        // 数据样式
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        // 设置数据居中对齐
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        //设置数据自动换行
        contentWriteCellStyle.setWrapped(true);
        //设置边框样式
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        // 设置数据背景色
        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());

        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        return horizontalCellStyleStrategy;
    }





    // 用于合并的拦截器
    public class CustomMergeStrategy extends AbstractRowWriteHandler {

        int row1;
        int row2;
        int col1;
        int col2;

        CustomMergeStrategy(int row1, int row2, int col1, int col2) {
            this.row1 = row1;
            this.row2 = row2;
            this.col1 = col1;
            this.col2 = col2;
        }


        @Override
        public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Integer relativeRowIndex, Boolean isHead) {
            Sheet sheet = writeSheetHolder.getSheet();
            CellRangeAddress cellRangeAddress = new CellRangeAddress(
                    row1, // first row (0-based)
                    row1, // last row  (0-based)
                    col1, // first column (0-based)
                    col2 // last column  (0-based)
            );
            sheet.addMergedRegionUnsafe(cellRangeAddress);
        }

    }

}



参考文献
EasyExcel无映射标题导出_easyexcel导出标题不展示-CSDN博客

apache poi 高版本 3.17后合并单元格的问题_addmergedregionunsafe-CSDN博客


http://www.kler.cn/news/324805.html

相关文章:

  • 租界服务器跑深度学习(一)服务器租用
  • vue3+AntvS2基本使用与导出excel
  • Golang | Leetcode Golang题解之第436题寻找右区间
  • 长文本溢出,中间位置显示省略号
  • 基于Node.js+Express+MySQL+VUE新闻网站管理系统的设计与实现
  • 小程序原生-地理定位功能介绍和实现
  • Service和Endpoints
  • 使用C#,MSSQL开发的钢结构加工系统
  • 如何在iPad上用Chrome实现无痕浏览
  • Acwing 快速幂
  • 力扣 简单 876.链表的中间结点
  • Leetcode面试经典150题-383.赎金信
  • 2024年【电工(高级)】考试题及电工(高级)考试内容
  • ISO 21434车辆网络安全风险评估的全面流程解析
  • 小柴冲刺软考中级嵌入式系统设计师系列二、嵌入式系统硬件基础知识(3)嵌入式系统的存储体系
  • 大模型落地需要一把“梯子”
  • 酒店智能开关的组成与功能
  • 【第十四周】PyTorch深度学习实践1
  • 浅说差分算法(上)
  • excel-VBA知识点记录
  • 服务器数据恢复—SAN环境下LUN映射出错导致文件系统一致性出错的数据恢复案例
  • 物联网系统中OLED屏主流驱动方案详解
  • 每日OJ题_牛客_HJ108求最小公倍数_C++_Java
  • unixODBC编程(四)插入数据
  • 【js】Node.js的fs的使用方法
  • 长沙某公司.Net高级开发面试题
  • 【C语言零基础入门篇 - 15】:单链表
  • 甄选范文“论应用服务器基础软件”,软考高级论文,系统架构设计师论文
  • 静态路由和默认路由(实验)
  • 海滨体育馆管理系统:SpringBoot实现技巧与案例