Java使用Excel模板导出文件,并合并

Java使用Excel模板导出文件,并合并

使用Excel模板导出文件感谢大神 吃茫茫@chimmhuang 的分享chimm.excel: chimm.excel 是一款能够简单操作 excel 的程序,该程序提供了如:填充excel模板数据、动态更改表格样式、导出excel等功能,降低了我们对excel的操作难度 (gitee.com)

合并Excel功能转自 Java使用POI实现多个excel合并成一个excel朱友斌的博客-CSDN博客java合并多个excel

1、pom中引入chimmhuang

<dependency>
           <groupId>com.github.chimmhuang</groupId>
           <artifactId>chimm.excel</artifactId>
           <version>1.2.0</version>
       </dependency>

2、方法类

package com.ruoyi.components.controller;

import com.github.chimmhuang.excel.ExcelHelper;
import com.github.chimmhuang.excel.tablemodel.ExcelWorkbook;
import com.github.chimmhuang.excel.tablemodel.SheetTable;
import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
* Created by xialing on 2022/5/12
*/
public class ExcelUtils {
   /**
    *
    * @param path   模板附件路径
    * @param sheet   模板sheet编号(从0开始)
    * @param dataMap 数据内容
    * @param hs     当前模板总行数(有多个动态表格时要根据这个值要确定存放位置)
    * @param ywzbid 文件名称
    */
   public static void createExcel(String path, int sheet, Map<String,Object> dataMap, int hs, String ywzbid){
       try {
           File file = new File(path);
           byte[] bytes = FileUtils.readFileToByteArray(file);

           // 通过 ExcelHelper 获取 excel 表格对象
           ExcelWorkbook excelWorkbook = ExcelHelper.createWorkbook(bytes);
           // 获取指定的 sheet 页(该对象即是我们设置好的表格模板)
           SheetTable table = excelWorkbook.getSheet(sheet);

           //动态设置表格
           int addrow = 0;
           for (String key : dataMap.keySet()) {
               if(key.contains("WZ")){
                   String wz =  dataMap.get(key).toString();
                   List<Map<String,Object>> list = (List<Map<String, Object>>) dataMap.get(key.substring(0,key.length()-2));
                   String[] arrwzs = wz.split(",");
                   int rowint = Integer.parseInt(arrwzs[0]);
                   int rowintadd = Integer.parseInt(arrwzs[0])+addrow;
                   List<com.github.chimmhuang.excel.tablemodel.Row> Rowlist = new ArrayList<>();
                   for (int i=rowint ; i<=hs ; i++){
                       com.github.chimmhuang.excel.tablemodel.Row row = table.getRow(i);
                       Rowlist.add(row);
                  }
                   com.github.chimmhuang.excel.tablemodel.Row rowrowint = table.getRow(rowint);
                   table.removeRowGE(rowintadd);
                   for (Map<String,Object> map:
                           list) {
                       com.github.chimmhuang.excel.tablemodel.Row copy = rowrowint.copy();
                       for (int j=1; j<arrwzs.length; j++){
                           copy.getCell(arrwzs[j]).setValue(map.get(""+arrwzs[j]));
                      }
                       table.appendRow(copy);
                  }
                   //这里合并单元格我是写死的只合并A列
                   table.mergeCell(rowintadd-1, rowintadd+list.size()-1, "A", "A");
                   if(Rowlist.size()>1){
                       for (int h=1;h<Rowlist.size();h++){
                           table.appendRow(Rowlist.get(h));
                      }
                  }
                   addrow = addrow + list.size()-1;
              }
          }



           // 将封装好的表格对象,填充到 excel 表格中
           ExcelHelper.fillInData(table, dataMap);

           // 将表格对象转换为二进制,resultBytes 即是最终想要的结果
           byte[] resultBytes = ExcelHelper.convert2Byte(table);
           File file1 = new File(System.getProperty("user.dir") + "\\"+ywzbid+sheet+".xlsx");
           OutputStream out = new FileOutputStream(file1);
           out.write(resultBytes);
           out.close();
      } catch (IOException e) {
           e.printStackTrace();
      }

  }

   /**
    * #合并多个excel文件
    * @param fileLists excel文件路径
    * @param path 目标文件保存目录
    * @param fileName 目标文件名称
    */
   public static void mergeExcel(List<String> fileLists, String path, String fileName) {
       // 创建新的excel工作簿
       XSSFWorkbook newExcelWorkBook = new XSSFWorkbook();
       // 遍历需要合并的excel文件
       for (String excelName : fileLists) {
           try (InputStream in = new FileInputStream(excelName)) {
               // 创建工作簿
               XSSFWorkbook tmpWorkBook = new XSSFWorkbook(in);
               // 获取工作簿中的Sheet个数
               int len = tmpWorkBook.getNumberOfSheets();
               if (len <= 1) {
                   XSSFSheet tmpSheet = tmpWorkBook.getSheetAt(0);
                   XSSFSheet newExcelSheet = newExcelWorkBook.createSheet(tmpSheet.getSheetName());
                   // 复制sheet内容
                   copyExcelSheet(newExcelWorkBook, tmpSheet, newExcelSheet);
              } else {
                   for (int i = 0; i < len; i++) {
                       XSSFSheet tmpSheet = tmpWorkBook.getSheetAt(i);
                       XSSFSheet newExcelSheet = newExcelWorkBook.createSheet(tmpSheet.getSheetName());
                       // 复制sheet内容
                       copyExcelSheet(newExcelWorkBook, tmpSheet, newExcelSheet);
                  }
              }
               // 关闭tmpWorkBook工作簿
               tmpWorkBook.close();
          } catch (IOException e) {
               e.printStackTrace();
          }
      }
       // 新生成的excel文件
       if (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")) {
           fileName += ".xlsx";
      }
       String excelFileName = path + File.separator + fileName;
       // 判断文件是否存在
       File excelFile = new File(excelFileName);
       if (excelFile.exists()) {
           // 存在则删除
           excelFile.delete();
      }
       // 使用输出流写出
       try (FileOutputStream fos = new FileOutputStream(excelFileName)) {
           newExcelWorkBook.write(fos);
           fos.flush();
      } catch (IOException e) {
           e.printStackTrace();
      } finally {
           try {
               newExcelWorkBook.close();
          } catch (IOException e) {
               e.printStackTrace();
          }
      }
       System.out.println("excel文件合并成功,合并后文件路径:" + excelFileName);
  }


   /**
    * #复制sheet到新的excel文件中
    * @param workbook excel工作簿
    * @param tmpSheet 来源sheet
    * @param newExcelSheet 新生成的sheet
    */
   public static void copyExcelSheet(XSSFWorkbook workbook, XSSFSheet tmpSheet, XSSFSheet newExcelSheet) {
       // 合并单元格
       mergeSheetAllRegion(tmpSheet, newExcelSheet);
       // 设置单元格列宽度
       // 获取最后一个单元格位置
       int len = tmpSheet.getRow(tmpSheet.getFirstRowNum()).getLastCellNum();
       for (int i = 0; i < len; i++) {
           newExcelSheet.setColumnWidth(i, tmpSheet.getColumnWidth(i));
      }
       // 复制每行内容
       Iterator<Row> it = tmpSheet.iterator();
       while (it.hasNext()) {
           XSSFRow tmpRow = (XSSFRow) it.next();
           // 创建新行
           XSSFRow newExcelRow = newExcelSheet.createRow(tmpRow.getRowNum());
           // 复制行
           copyExcelRow(workbook, tmpRow, newExcelRow);
      }
  }

   /**
    * #合并单元格
    * @param tmpSheet 来源sheet
    * @param newExcelSheet 目标sheet
    */
   private static void mergeSheetAllRegion(XSSFSheet tmpSheet, XSSFSheet newExcelSheet) {
       int num = tmpSheet.getNumMergedRegions();
       CellRangeAddress cellRange = null;
       for (int i = 0; i < num; i++) {
           cellRange = tmpSheet.getMergedRegion(i);
           newExcelSheet.addMergedRegion(cellRange);
      }
  }

   /**
    * #复制excel中的行到新的sheet中
    * @param workbook 目标工作簿
    * @param tmpRow 来源excel行
    * @param newExcelRow 目标excel行
    */
   public static void copyExcelRow(XSSFWorkbook workbook, XSSFRow tmpRow, XSSFRow newExcelRow) {
       // 设置行高
       newExcelRow.setHeight(tmpRow.getHeight());
       // 获取所有列
       Iterator<Cell> it = tmpRow.cellIterator();
       while (it.hasNext()) {
           XSSFCell tmpCell = (XSSFCell) it.next();
           // 创建单元格
           XSSFCell newExcelCell = newExcelRow.createCell(tmpCell.getColumnIndex());
           // 复制单元格
           copyExcelCell(workbook, tmpCell, newExcelCell);
      }
  }

   /**
    * #复制单元格
    * @param workbook 目标工作簿
    * @param tmpCell 来源excel单元格
    * @param newExcelCell 目标excel单元格
    */
   public static void copyExcelCell(XSSFWorkbook workbook, XSSFCell tmpCell, XSSFCell newExcelCell) {
       XSSFCellStyle newExcelStyle = workbook.createCellStyle();
       // 复制单元格样式
       newExcelStyle.cloneStyleFrom(tmpCell.getCellStyle());
       // 单元格样式
       newExcelCell.setCellStyle(newExcelStyle);
       if (tmpCell.getCellComment() != null) {
           newExcelCell.setCellComment(tmpCell.getCellComment());
      }
       // 不同数据类型处理
       CellType tmpCellType = tmpCell.getCellType();
       newExcelCell.setCellType(tmpCellType);
       if (tmpCellType == CellType.NUMERIC) {
           if (DateUtil.isCellDateFormatted(tmpCell)) {
               newExcelCell.setCellValue(tmpCell.getDateCellValue());
          } else {
               newExcelCell.setCellValue(tmpCell.getNumericCellValue());
          }
      } else if (tmpCellType == CellType.STRING) {
           newExcelCell.setCellValue(tmpCell.getRichStringCellValue());
      } else if (tmpCellType == CellType.BLANK) {
      } else if (tmpCellType == CellType.BOOLEAN) {
           newExcelCell.setCellValue(tmpCell.getBooleanCellValue());
      } else if (tmpCellType == CellType.ERROR) {
           newExcelCell.setCellErrorValue(tmpCell.getErrorCellValue());
      } else if (tmpCellType == CellType.FORMULA) {
           newExcelCell.setCellFormula(tmpCell.getCellFormula());
      } else {
      }
  }
}

3、调用方法

public void export()
  {
      //配置封面sheet数据
      Map<String,Object> fmMap = new HashMap<>();
      fmMap.put("F_jlbzmc","1");
      fmMap.put("F_jlbzdm","2");
      fmMap.put("F_qymc","3");
      fmMap.put("F_tyshxydm","4");
      fmMap.put("F_dwdz","5");
      fmMap.put("F_yzbm","6");
      fmMap.put("F_jlbzfzr","7");

      Map<String,Object> hjryMap = new HashMap<>();

      //配置环境、人员sheet
      //环境
      List<Map<String,Object>> hjlist = new ArrayList<>();
      //环境人员都是动态表格,这里是设置各个填入表格的位置
      for (int i=1 ; i <=5 ; i++){
          Map<String,Object> map = new HashMap<>();
          map.put("B",i);
          map.put("C","HJ"+i);
          map.put("E","HJ"+i);
          map.put("G","HJ"+i);
          map.put("I","HJ"+i);
          hjlist.add(map);
      }
      hjryMap.put("hjlist",hjlist);
      //这里的2是动态表格开始存放的位置,后面的字母是各个字段的位置
      hjryMap.put("hjlistWZ","2,B,C,E,G,I");

      //人员
      List<Map<String,Object>> rylist = new ArrayList<>();
      //环境人员都是动态表格,这里是设置各个填入表格的位置
      for (int i=1 ; i <=7 ; i++){
          Map<String,Object> rymap = new HashMap<>();
          rymap.put("B","RY"+i);
          rymap.put("C","RY"+i);
          rymap.put("D","RY"+i);
          rymap.put("E","RY"+i);
          rymap.put("F","RY"+i);
          rymap.put("G","RY"+i);
          rymap.put("I","RY"+i);
          rylist.add(rymap);
      }
      hjryMap.put("rylist",rylist);
      hjryMap.put("rylistWZ","4,B,C,D,E,F,G,I");

      //生成文书
      ExcelUtils.createExcel(System.getProperty("user.dir")+"/jlsqs.xlsx",0,fmMap,14,"test");
      ExcelUtils.createExcel(System.getProperty("user.dir")+"/jlsqs.xlsx",1,hjryMap,4,"test");

      //合并文书
      List<String> fileLists = Arrays.asList(new String[] {
              System.getProperty("user.dir") + "\\"+"test0.xlsx",
              System.getProperty("user.dir") + "\\"+"test1.xlsx"
      });
      String path = System.getProperty("user.dir");
      String fileName = "test";
      ExcelUtils.mergeExcel(fileLists, path, fileName);
  }
 

模板

导出效果

posted @   sumling  阅读(394)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示