NPOI 多个Excel合并为一个Excel

本文介绍如何利用NPOI库在C#中合并多个Excel文件为一个。通过搜索并安装NPOI,添加必要的引用,可以实现读取指定路径下的多个Excel文件,并将它们合并到一个工作簿中,每个文件作为单独的工作表。最后,合并后的Excel文件会被发送到客户端进行下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现代码

Nuget 中搜索并安装NPOI

添加引用using NPOI.HSSF.UserModel;

            var fullWork = new HSSFWorkbook();//最终的合并excel
            string exportReports = hidExportReports.Value;//需要合并的Excel文件路径
            if (!string.IsNullOrEmpty(exportReports))
            {
                var reportArrary = exportReports.Split(',');
                try
                {                   
                    for (int i = 0; i < reportArrary.Length; i++)
                    {
                        string sheetName = Path.GetFileNameWithoutExtension(reportArrary[i]).Split('_')[1];//获取sheet名称
                        var excelStream = new FileStream(reportArrary[i], FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                        var workbook = new HSSFWorkbook(excelStream);//读取excel文件
                        HSSFSheet sheet = workbook.GetSheetAt(0) as HSSFSheet;  //获取第一个工作表(sheet)
                        sheet.CopyTo(fullWork, sheetName, true, true);//将报表合并至综合报表中
                    }
                    var stream = new MemoryStream();
                    fullWork.Write(stream);
                    byte[] bytes = stream.ToArray();
                    // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
                    Response.Buffer = true;
                    Response.Clear();
                    Response.ContentType = "application/vnd.ms-excel";
                    String filename = HttpUtility.UrlEncode("综合报表", Encoding.UTF8);
                    Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".xls");
                    Response.BinaryWrite(bytes); // create the file
                    Response.Flush(); // send it to the client to download                   
                }
                catch
                {

                }
                finally
                {
                    //删除excel文件
                    for (int i = 0; i < reportArrary.Length; i++)
                    {
                        File.Delete(reportArrary[i]);
                    }
                }
            }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值