将多个excel合并成一个包含多个sheet的excel

先定义一个工具类

package com.lmbx.edu.utils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.util.Iterator;

public class POIUtils {

    public class XSSFDateUtil extends DateUtil {

    }
    public static void copyCellStyle(XSSFCellStyle fromStyle, XSSFCellStyle toStyle) {

        toStyle.cloneStyleFrom(fromStyle);//此一行代码搞定
        //下面统统不用
        /*
        //对齐方式
        toStyle.setAlignment(fromStyle.getAlignment());
        //边框和边框颜色
        toStyle.setBorderBottom(fromStyle.getBorderBottom());
        toStyle.setBorderLeft(fromStyle.getBorderLeft());
        toStyle.setBorderRight(fromStyle.getBorderRight());
        toStyle.setBorderTop(fromStyle.getBorderTop());
        toStyle.setTopBorderColor(fromStyle.getTopBorderColor());
        toStyle.setBottomBorderColor(fromStyle.getBottomBorderColor());
        toStyle.setRightBorderColor(fromStyle.getRightBorderColor());
        toStyle.setLeftBorderColor(fromStyle.getLeftBorderColor());
        //背景和前景
        //toStyle.setFillPattern(fromStyle.getFillPattern());  //填充图案,不起作用,转为黑色
        toStyle.setFillBackgroundColor(fromStyle.getFillBackgroundColor());  //不起作用
        toStyle.setFillForegroundColor(fromStyle.getFillForegroundColor());
        toStyle.setDataFormat(fromStyle.getDataFormat());  //数据格式
        //toStyle.setFont(fromStyle.getFont());  //不起作用
        toStyle.setHidden(fromStyle.getHidden());
        toStyle.setIndention(fromStyle.getIndention());//首行缩进
        toStyle.setLocked(fromStyle.getLocked());
        toStyle.setRotation(fromStyle.getRotation());//旋转
        toStyle.setVerticalAlignment(fromStyle.getVerticalAlignment());  //垂直对齐
        toStyle.setWrapText(fromStyle.getWrapText()); //文本换行
        */
    }
    public 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);
        }
    }

    public static void copyCell(XSSFWorkbook wb,XSSFCell fromCell, XSSFCell toCell) {
        XSSFCellStyle newstyle=wb.createCellStyle();
        copyCellStyle(fromCell.getCellStyle(), newstyle);
        //toCell.setEncoding(fromCell.getEncoding());
        //样式
        toCell.setCellStyle(newstyle);
        if (fromCell.getCellComment() != null) {
            toCell.setCellComment(fromCell.getCellComment());
        }
        // 不同数据类型处理
        int fromCellType = fromCell.getCellType();
        toCell.setCellType(fromCellType);
        if (fromCellType == XSSFCell.CELL_TYPE_NUMERIC) {
            if (XSSFDateUtil.isCellDateFormatted(fromCell)) {
                toCell.setCellValue(fromCell.getDateCellValue());
            } else {
                toCell.setCellValue(fromCell.getNumericCellValue());
            }
        } else if (fromCellType == XSSFCell.CELL_TYPE_STRING) {
            toCell.setCellValue(fromCell.getRichStringCellValue());
        } else if (fromCellType == XSSFCell.CELL_TYPE_BLANK) {
            // nothing21
        } else if (fromCellType == XSSFCell.CELL_TYPE_BOOLEAN) {
            toCell.setCellValue(fromCell.getBooleanCellValue());
        } else if (fromCellType == XSSFCell.CELL_TYPE_ERROR) {
            toCell.setCellErrorValue(fromCell.getErrorCellValue());
        } else if (fromCellType == XSSFCell.CELL_TYPE_FORMULA) {
            toCell.setCellFormula(fromCell.getCellFormula());
        } else { // nothing29
        }

    }

    public 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);
        }
    }
    public static void copySheet(XSSFWorkbook wb,XSSFSheet fromSheet, XSSFSheet toSheet) {
        mergeSheetAllRegion(fromSheet, toSheet);
        //设置列宽
        for(int i=0;i<=fromSheet.getRow(fromSheet.getFirstRowNum()).getLastCellNum();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);
        }
    }


}

具体的contrller可以这样写

@RequestMapping("/excel")
    public void excel() throws IOException {
//将所有类型的尽调excel文件合并成一个excel文件
        XSSFWorkbook newExcelCreat = new XSSFWorkbook();
        List<String> fileNameList=new ArrayList();
//这是一个要合并的excel文件地址集合
        fileNameList.add("edu-server/target/classes/excel/211幼儿园.xlsx");
        fileNameList.add("edu-server/target/classes/excel/213初中.xlsx");
        for(String fromExcelName:fileNameList) {//遍历每个源excel文件,fileNameList为源文件的名称集合

            InputStream in = new FileInputStream(fromExcelName);
            XSSFWorkbook fromExcel = new XSSFWorkbook(in);
            for(int i = 0; i < fromExcel.getNumberOfSheets(); i++) {//遍历每个sheet
                XSSFSheet oldSheet = fromExcel.getSheetAt(i);
                XSSFSheet newSheet = newExcelCreat.createSheet(oldSheet.getSheetName());
                POIUtils.copySheet(newExcelCreat, oldSheet, newSheet);
            }
        }
        //文件合并后的地址及名称
        String allFileName="总文件.xlsx";
        FileOutputStream fileOut = new FileOutputStream(allFileName);
        newExcelCreat.write(fileOut);
        fileOut.flush();
        fileOut.close();
        //删除各个源文件
        for(String fromExcelName:fileNameList) {//遍历每个源excel文件
            File file=new File(fromExcelName);
            if(file.exists()){
                file.delete();
            }
        }

    }
您好!要将多个Excel文件合并一个Excel文件,可以使用VBA编写脚本来实现。以下是一个示例代码,您可以根据自己的需求进行修改: ``` Sub MergeExcelFiles() Dim path As String, fileName As String, sheet As Worksheet, total As Integer Dim r As Range, cell As Range, row As Range, col As Range '设置合并后的文件名和路径 path = "C:\合并后的文件.xlsx" fileName = Dir("C:\需要合并的文件夹\*.xlsx") total = 0 '打开第一个文件 Do While fileName <> "" Workbooks.Open fileName:= "C:\需要合并的文件夹\" & fileName, ReadOnly:=True For Each sheet In ActiveWorkbook.Sheets '复制每个工作表的内容到新的工作表 sheet.Copy After:=ThisWorkbook.Sheets(1) Next sheet '关闭当前工作簿 Workbooks(fileName).Close '获取下一个文件名 fileName = Dir() total = total + 1 Loop '删除新工作表中的所有空行 For Each row In ActiveSheet.UsedRange.Rows If Application.CountA(row) = 0 Then row.Delete Next row '删除新工作表中的所有空列 For Each col In ActiveSheet.UsedRange.Columns If Application.CountA(col) = 0 Then col.Delete Next col '保存合并后的文件 ActiveWorkbook.SaveAs Filename:=path, FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False ActiveWorkbook.Close MsgBox "共合并了 " & total & " 个Excel文件。" End Sub ``` 在这个示例代码中,我们将需要合并Excel文件放在一个文件夹中,然后通过循环读取文件夹中的每个Excel文件,将每个工作表的内容复制到新的工作表中。然后,我们删除新工作表中的所有空行和空列,最后将新工作表保存为一个文件。 请注意,在运行代码之前,请确保将“合并后的文件名和路径”和“需要合并的文件夹”更改为您的实际路径和文件名。另外,该代码适用于Excel 2007及以上版本。如果您使用的是较早的版本,请将“xlOpenXMLWorkbook”更改为适当的文件格式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值