利用NPOI合并多个Excel文件到一个新的Excel

using NPOI.HSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;   

 public static void MergeExcel(List files, string destinationFile)
        {
            HSSFWorkbook product = new HSSFWorkbook();
            int itemIndex = 1;
            foreach (var strFile in files)
            {
                if (!File.Exists(strFile.ReportFilePath))
                {
                    continue;
                }
                //NPOICOPY(strFile, i, destinationFile);
                byte[] byteArray = File.ReadAllBytes(strFile.ReportFilePath);
                using (MemoryStream stream = new MemoryStream())
                {
                    stream.Write(byteArray, 0, (int)byteArray.Length);
                    HSSFWorkbook book1 = new HSSFWorkbook(stream);
                    for (int i = 0; i < book1.NumberOfSheets; i++)
                    {
                        HSSFSheet sheet1 = book1.GetSheetAt(i) as HSSFSheet;
                        //avoid sheet has same name
                        string reportName = strFile.ReportTitleName;
                        if (string.IsNullOrEmpty(reportName))
                        {
                            reportName = "";
                        }
                        else
                        {
                            reportName = reportName.Replace("/", "").Replace("\\", "").Replace("[", "").Replace("]", "");
                        }
                        sheet1.CopyTo(product, reportName + "_Sheet0" + itemIndex, true, true);
                        itemIndex++;
                    }
                }
            }
            using (FileStream fs = new FileStream(destinationFile, FileMode.Create, FileAccess.Write))
            {
                product.Write(fs);
            }
        }
Nuget install NPOI

Excel Sheet Name max length is 31. eg.  abcdedfhijklmnopqrstuvwxyz12345

当长度超过31时,会自动截断。

利用NPOI合并多个Excel文件到一个新的Excel_第1张图片


你可能感兴趣的:(Excel,C#)