首页 > 其他分享 >EasyExcel合并单元格

EasyExcel合并单元格

时间:2023-09-26 09:59:33浏览次数:38  
标签:demoDataList EasyExcel 单元格 合并 DemoData excelWriter new data

普通不合并单元格
public static void writeExcel() {
    // 写excel的路径,当前项目路径下
    String fileName = getPath();
    // 构建ExcelWriter
    ExcelWriter excelWriter = EasyExcel.write(fileName).excelType(ExcelTypeEnum.XLSX).build();

    // 构建sheet
    WriteSheet writeSheet = EasyExcel.writerSheet("模板1").head(DemoData.class).build();
    // 写sheet
    excelWriter.write(data1(), writeSheet);
    excelWriter.finish();
  }

  private static String getPath() {
    return System.getProperty("user.dir") + "/" + System.currentTimeMillis() + ".xlsx";
  }

  private static List<DemoData> data1() {
    List<DemoData> list = Lists.newArrayList();
    for (int i = 0; i < 3; i++) {
      DemoData data = new DemoData();
      data.setString("字符串" + 1);
      data.setDate(new Date());
      data.setDoubleData(0.56);
      list.add(data);
    }
    for (int i = 0; i < 3; i++) {
      DemoData data = new DemoData();
      data.setString("字符串" + 2);
      data.setDate(new Date());
      data.setDoubleData(0.56);
      list.add(data);
    }
    for (int i = 0; i < 4; i++) {
      DemoData data = new DemoData();
      data.setString("字符串" + 3);
      data.setDate(new Date());
      data.setDoubleData(0.57);
      list.add(data);
    }
    return list;
  }

  public static void main(String[] args) {
    writeExcel();
  }
合并单元格
  // 自定义合并策略 该类继承了AbstractMergeStrategy抽象合并策略,需要重写merge()方法
  public static class CustomMergeStrategy extends AbstractMergeStrategy {

    /**
     * 分组,每几行合并一次
     */
    private List<Integer> exportFieldGroupCountList;

    /**
     * 目标合并列index
     */
    private Integer targetColumnIndex;

    // 需要开始合并单元格的首行index
    private Integer rowIndex;

    // exportDataList为待合并目标列的值 
    public CustomMergeStrategy(List<String> exportDataList, Integer targetColumnIndex) {
      this.exportFieldGroupCountList = getGroupCountList(exportDataList);
      this.targetColumnIndex = targetColumnIndex;
    }


    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex) {

      if (null == rowIndex) {
        rowIndex = cell.getRowIndex();
      }
      // 仅从首行以及目标列的单元格开始合并,忽略其他
      if (cell.getRowIndex() == rowIndex && cell.getColumnIndex() == targetColumnIndex) {
        mergeGroupColumn(sheet);
      }
    }

    private void mergeGroupColumn(Sheet sheet) {
      int rowCount = rowIndex;
      for (Integer count : exportFieldGroupCountList) {
        if(count == 1) {
          rowCount += count;
          continue ;
        }
        // 合并单元格
        CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCount, rowCount + count - 1, targetColumnIndex, targetColumnIndex);
        sheet.addMergedRegionUnsafe(cellRangeAddress);
        rowCount += count;
      }
    }

    // 该方法将目标列根据值是否相同连续可合并,存储可合并的行数 
    private List<Integer> getGroupCountList(List<String> exportDataList){
      if (CollectionUtils.isEmpty(exportDataList)) {
        return new ArrayList<>();
      }

      List<Integer> groupCountList = new ArrayList<>();
      int count = 1;

      for (int i = 1; i < exportDataList.size(); i++) {
        if (exportDataList.get(i).equals(exportDataList.get(i - 1))) {
          count++;
        } else {
          groupCountList.add(count);
          count = 1;
        }
      }
      // 处理完最后一条后
      groupCountList.add(count);
      return groupCountList;
    }
  }

// 修改WriteSheet的代码如下 
  public static void writeExcel() {
    String fileName = getPath();
    ExcelWriter excelWriter = EasyExcel.write(fileName).excelType(ExcelTypeEnum.XLSX).build();

    List<DemoData> demoDataList = data1();
    // 写sheet的时候注册相应的自定义合并单元格策略
    WriteSheet writeSheet = EasyExcel.writerSheet("模板1").head(DemoData.class)
    .registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(DemoData::getString).collect(Collectors.toList()), 0))
    .build();
    excelWriter.write(demoDataList, writeSheet);
    excelWriter.finish();
  }

image

同理若要合并第三列的数据,则可以在注册一个sheet写处理器,代码如下

public static void writeExcel() {
    String fileName = getPath();
    ExcelWriter excelWriter = EasyExcel.write(fileName).excelType(ExcelTypeEnum.XLSX).build();

    List<DemoData> demoDataList = data1();
    WriteSheet writeSheet = EasyExcel.writerSheet("模板1").head(DemoData.class)
    .registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(DemoData::getString).collect(Collectors.toList()), 0))
    .registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(o -> o.getDoubleData().toString()).collect(Collectors.toList()), 2))
    .build();
    excelWriter.write(demoDataList, writeSheet);
    excelWriter.finish();
  }

image

1.3 写多个sheet
 public static void writeExcel() {
    String fileName = getPath();
    ExcelWriter excelWriter = EasyExcel.write(fileName).excelType(ExcelTypeEnum.XLSX).build();

    List<DemoData> demoDataList = data1();
    WriteSheet writeSheet = EasyExcel.writerSheet("模板1").head(DemoData.class)
    .registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(DemoData::getString).collect(Collectors.toList()), 0))
    .registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(o -> o.getDoubleData().toString()).collect(Collectors.toList()), 2))
    .build();
    excelWriter.write(demoDataList, writeSheet);

    WriteSheet writeSheet1 = EasyExcel.writerSheet("模板2").head(DemoData.class).build();
    excelWriter.write(data1(), writeSheet1);
    excelWriter.finish();
  }

image

1.4 WriteTable

若业务需求要求在同一个sheet中写多个表,就需要用到WriteTable了。只定义一个WriteSheet,有几个表就定义几个WriteTable

 public static void writeExcel01() {
    String fileName = getPath();
    ExcelWriter excelWriter = EasyExcel.write(fileName).excelType(ExcelTypeEnum.XLSX).build();
    WriteSheet writeSheet = EasyExcel.writerSheet("模板").needHead(Boolean.FALSE).build();

    List<DemoData> demoDataList = data1();
    // 需要表头设置为true,WriteTable一些属性会继承自WriteSheet
    WriteTable writeTable = EasyExcel.writerTable(1).head(DemoData.class).needHead(Boolean.TRUE)
        .registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(DemoData::getString).collect(Collectors.toList()), 0))
        .registerWriteHandler(new CustomMergeStrategy(demoDataList.stream().map(o -> o.getDoubleData().toString()).collect(Collectors.toList()), 2))
        .build();
    excelWriter.write(demoDataList, writeSheet, writeTable);

    WriteTable writeTable1 = EasyExcel.writerTable(2).head(DemoData.class).needHead(Boolean.TRUE).build();
    excelWriter.write(data1(), writeSheet, writeTable1);
    excelWriter.finish();
  }

image

本文内容来源于网络,版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如侵犯了您的权益,请联系我,将立刻删除。

标签:demoDataList,EasyExcel,单元格,合并,DemoData,excelWriter,new,data
From: https://www.cnblogs.com/fchhk-blog/p/17729413.html

相关文章

  • EasyExcel动态表头导出(支持多级表头)
    EasyExcel动态表头导出(支持多级表头)在很多业务场景中,都会应用到动态表头的导出,也会涉及到多级表头的导出,如下图所示通过EasyExcel,我们可以快速实现这一需求,具体代码如下DynamicHeaderimportjava.util.List;/***@Author:<ahref="mailto:[email protected]">Fxsen</a>......
  • leetcode21. 合并两个有序链表
    合并两个有序链表题目链接21.合并两个有序链表将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。示例1:输入:l1=[1,2,4],l2=[1,3,4]输出:[1,1,2,3,4,4]示例2:输入:l1=[],l2=[]输出:[]示例3:输入:l1=[],l2=[0]输出:[0......
  • 194_win7_10任务栏合并但不隐藏标签
    这是一篇原发布于2020-01-2310:28:00得益小站的文章,备份在此处。前言我们都知道Windows的任务栏有个合并、隐藏标签的功能。但Windows提供的三个选项中,就是少了一个不合并但隐藏标签的选项,本文就来解决这个问题。不想看原理,只想快速解决的同学,可以翻到最后,有一键设置的方法。......
  • P1631 序列合并
    P1631序列合并思路思路一题目要求的是二维的,太麻烦,所以我们可以将其用一维划分,将每一组都变成线性的,那线性的就很好求了,直接排序然后从前往后算即可,那么就可以将这\(n\)组合并,但如果是整个都算出来再合并就会是\(O(n^2)\)的,所以可以只记录当前的,那么对于当前的最小的状态,......
  • ClickHouse数据表合并与性能优化方法探讨与案例研究分享
    前言ClickHouse是一款高性能的列式数据库,其在海量数据处理方面具有很强的优势。但是,在实际应用中,我们经常需要对多个数据表进行合并,以便更好地进行数据分析和挖掘。本文将探讨ClickHouse的数据表合并与性能优化方法,并结合实际案例进行分享。数据表合并在ClickHouse中,数据表合并......
  • Leetcode刷题21.合并两个有序链表
    将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。  示例1:输入:l1=[1,2,4],l2=[1,3,4]输出:[1,1,2,3,4,4]示例2:输入:l1=[],l2=[]输出:[]示例3:输入:l1=[],l2=[0]输出:[0] 提示:两个链表的节点数目......
  • python的pandas库:合并数据
    在Pandas中,如果你有两个数据框(DataFrames),且它们的列数和列名都相同,你可以使用concat或merge函数将它们合并。以下是具体步骤:首先,导入Pandas库:importpandasaspd创建两个列数和列名都相同的数据框:df1=pd.DataFrame({'A':['A0','A1','A2','A3'],'B':[�......
  • 表格动态合并,序号连续
    效果:<el-table:data="tableData"style="width:100%"v-loading="tableDataLoading":header-cell-style="{background:'#FAFAFA'}":span-method="objectSpanMethod"......
  • ClickHouse(15)ClickHouse合并树MergeTree家族表引擎之GraphiteMergeTree详细解析
    GraphiteMergeTree该引擎用来对Graphite数据(图数据)进行瘦身及汇总。对于想使用ClickHouse来存储Graphite数据的开发者来说可能有用。如果不需要对Graphite数据做汇总,那么可以使用任意的ClickHouse表引擎;但若需要,那就采用GraphiteMergeTree引擎。它能减少存储空间,同时能提高Grap......
  • git多个commit合并成一个
    前言一个功能有多个commit要合并成一个更加美观操作打开gitbase1.输入gitlog-8  //查看前8条提交2.输入gitrebase-iHEAD~3  //表示最近的3条合并成一条3.输入完后界面如下,按i进入编译模式,将第2,3个pick改为s,表示将后2条合并到第一条中,然后按esc退出编译模式,然后......