1. 程式人生 > 實用技巧 >JAVA用poi實現多個excel的Sheet合併

JAVA用poi實現多個excel的Sheet合併

前言

專案中遇到需求,需要將多個excel的sheet合併到一個excel裡面。網上看了一下文章,但是很多都是斷章取義,不是程式碼不全,就是jar包版本不同一,為此自己解決這個問題後,把解決方案記錄下來,供後來的童鞋參考:

第一步:匯入poi相關jar包

 <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi-ooxml</artifactId>
         <version>4.1.2</version
> </dependency>

第二步:複製工具類

import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

import java.io.*;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/** * @description: 多個Excel合併Sheet * @author: wyj * @time: 2020/9/18 15:28 */ public class ExcelUtil { public static void main(String[] args) { List<String> list = Arrays.asList( new File("D:\\test\\a.xlsx").toString(), new File("D:\\test\\b.xlsx").toString(),
new File("D:\\test\\c.xlsx").toString() ); mergexcel(list,"楊洪-家庭貸-20190908(報告).xlsx","D:\\test"); System.out.println("OJBK"); } /** * * 合併多個ExcelSheet * * @param files 檔案字串(file.toString)集合,按順序進行合併,合併的Excel中Sheet名稱不可重複 * @param excelName 合併後Excel名稱(包含字尾.xslx) * @param dirPath 儲存目錄 * @return * @Date: 2020/9/18 15:31 */ public static void mergexcel(List<String> files, String excelName, String dirPath) { XSSFWorkbook newExcelCreat = new XSSFWorkbook(); // 遍歷每個源excel檔案,TmpList為原始檔的名稱集合 for (String fromExcelName : files) { try (InputStream in = new FileInputStream(fromExcelName)) { XSSFWorkbook fromExcel = new XSSFWorkbook(in); int length = fromExcel.getNumberOfSheets(); if (length <= 1) { //長度為1時 XSSFSheet oldSheet = fromExcel.getSheetAt(0); XSSFSheet newSheet = newExcelCreat.createSheet(oldSheet.getSheetName()); copySheet(newExcelCreat, oldSheet, newSheet); } else { for (int i = 0; i < length; i++) {// 遍歷每個sheet XSSFSheet oldSheet = fromExcel.getSheetAt(i); XSSFSheet newSheet = newExcelCreat.createSheet(oldSheet.getSheetName()); copySheet(newExcelCreat, oldSheet, newSheet); } } } catch (IOException e) { e.printStackTrace(); } } // 定義新生成的xlxs表格檔案 String allFileName = dirPath + File.separator + excelName; try (FileOutputStream fileOut = new FileOutputStream(allFileName)) { newExcelCreat.write(fileOut); fileOut.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { newExcelCreat.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 合併單元格 * * @param fromSheet * @param toSheet */ private static void mergeSheetAllRegion(XSSFSheet fromSheet, XSSFSheet toSheet) { int num = fromSheet.getNumMergedRegions(); CellRangeAddress cellR = null; for (int i = 0; i < num; i++) { cellR = fromSheet.getMergedRegion(i); toSheet.addMergedRegion(cellR); } } /** * 複製單元格 * * @param wb * @param fromCell * @param toCell */ private static void copyCell(XSSFWorkbook wb, XSSFCell fromCell, XSSFCell toCell) { XSSFCellStyle newstyle = wb.createCellStyle(); // 複製單元格樣式 newstyle.cloneStyleFrom(fromCell.getCellStyle()); // 樣式 toCell.setCellStyle(newstyle); if (fromCell.getCellComment() != null) { toCell.setCellComment(fromCell.getCellComment()); } // 不同資料型別處理 CellType fromCellType = fromCell.getCellType(); toCell.setCellType(fromCellType); if (fromCellType == CellType.NUMERIC) { if (DateUtil.isCellDateFormatted(fromCell)) { toCell.setCellValue(fromCell.getDateCellValue()); } else { toCell.setCellValue(fromCell.getNumericCellValue()); } } else if (fromCellType == CellType.STRING) { toCell.setCellValue(fromCell.getRichStringCellValue()); } else if (fromCellType == CellType.BLANK) { // nothing21 } else if (fromCellType == CellType.BOOLEAN) { toCell.setCellValue(fromCell.getBooleanCellValue()); } else if (fromCellType == CellType.ERROR) { toCell.setCellErrorValue(fromCell.getErrorCellValue()); } else if (fromCellType == CellType.FORMULA) { toCell.setCellFormula(fromCell.getCellFormula()); } else { // nothing29 } } /** * 行復制功能 * * @param wb * @param oldRow * @param toRow */ private static void copyRow(XSSFWorkbook wb, XSSFRow oldRow, XSSFRow toRow) { toRow.setHeight(oldRow.getHeight()); for (Iterator cellIt = oldRow.cellIterator(); cellIt.hasNext(); ) { XSSFCell tmpCell = (XSSFCell) cellIt.next(); XSSFCell newCell = toRow.createCell(tmpCell.getColumnIndex()); copyCell(wb, tmpCell, newCell); } } /** * Sheet複製 * * @param wb * @param fromSheet * @param toSheet */ private static void copySheet(XSSFWorkbook wb, XSSFSheet fromSheet, XSSFSheet toSheet) { mergeSheetAllRegion(fromSheet, toSheet); // 設定列寬 int length = fromSheet.getRow(fromSheet.getFirstRowNum()).getLastCellNum(); for (int i = 0; i <= length; i++) { toSheet.setColumnWidth(i, fromSheet.getColumnWidth(i)); } for (Iterator rowIt = fromSheet.rowIterator(); rowIt.hasNext(); ) { XSSFRow oldRow = (XSSFRow) rowIt.next(); XSSFRow newRow = toSheet.createRow(oldRow.getRowNum()); copyRow(wb, oldRow, newRow); } } }
View Code

附加:提供一個建立空白excel的方法

 /**
     * *建立空的excel檔案,可自定義sheet名稱
     *
     * @param filePath  檔案路徑
     * @param sheetList  sheet名稱集合(名稱不可重複)
     * @return
     * @Date: 2020/9/21 17:36
     */
    public static void createBlankExcel(String filePath, List<String> sheetList) {
        try (FileOutputStream out = new FileOutputStream(new File(filePath))) {
            XSSFWorkbook workbook = new XSSFWorkbook();
            if (sheetList != null && sheetList.size() > 0) {
                for (String sheet : sheetList) {
                    workbook.createSheet(sheet);
                }
            } else {
                // 預設3個sheet
                workbook.createSheet("sheet1");
                workbook.createSheet("sheet2");
                workbook.createSheet("sheet3");
            }
            XSSFCellStyle cellStyle = workbook.createCellStyle();
            XSSFFont font = workbook.createFont();
            font.setColor(Font.COLOR_RED);
            cellStyle.setFont(font);
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }