您的位置:首页 > 其它

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

2018-02-01 09:11 711 查看
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<PDFSourceFileConfig> 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 namestring 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 NPOIExcel Sheet Name max length is 31. eg.  abcdedfhijklmnopqrstuvwxyz12345当长度超过31时,会自动截断。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Excel