繁体   English   中英

在C#中合并Excel工作表的替代方法

[英]Alternative way of merging excel worksheets in c#

我想知道是否还有另一种方法可以在不使用Microsoft.Office.Interop.Excel;情况下将多个excel工作表合并为一个Microsoft.Office.Interop.Excel; 命名空间。

我目前正在为此使用C#,因此需要在C#中找到另一种方法。

这样做的原因是我无法控制的,但是我想知道是否还有另一种方法可以做到这一点。

我乐于接受任何想法和任何帮助。

以下是到目前为止的C#(可以正常运行)

using Microsoft.Office.Interop.Excel;

namespace MergeWorkBooks
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string mergedWorkbookName = "MergedWorkbook.xlsx";
            string[] sourceFilePaths = new string[] { "STORE_OPS_00_COVER.xlsx", "STORE_OPS_01_STOCK_ACCOUNT_MOVEMENT_REPORT.xlsx", "STORE_OPS_02_SALES_SUMMARY.xlsx", "STORE_OPS_03_DISPATCHES.xlsx" };
            string destinationFilePath = @"C:\Users\bb\Documents\" + mergedWorkbookName;

            MergeWorkbooks(destinationFilePath, sourceFilePaths);
        }

        public static void MergeWorkbooks(string destinationFilePath, params string[] sourceFilePaths)
        {
            var app = new Application();
            app.DisplayAlerts = false; // No prompt when overriding

            // Create a new workbook (index=1) and open source workbooks (index=2,3,...)
            Workbook destinationWb = app.Workbooks.Add();
            foreach (var sourceFilePath in sourceFilePaths)
            {
                app.Workbooks.Add(sourceFilePath);
            }

            // Copy all worksheets
            Worksheet after = destinationWb.Worksheets[1];
            for (int wbIndex = app.Workbooks.Count; wbIndex >= 2; wbIndex--)
            {
                Workbook wb = app.Workbooks[wbIndex];
                for (int wsIndex = wb.Worksheets.Count; wsIndex >= 1; wsIndex--)
                {
                    Worksheet ws = wb.Worksheets[wsIndex];
                    ws.Copy(After: after);
                }
            }

            // Close source documents before saving destination. Otherwise, save will fail
            for (int wbIndex = 2; wbIndex <= app.Workbooks.Count; wbIndex++)
            {
                Workbook wb = app.Workbooks[wbIndex];
                wb.Close();
            }

            // Delete default worksheet
            after.Delete();

            // Save new workbook
            destinationWb.SaveAs(destinationFilePath);
            destinationWb.Close();

            app.Quit();
        }
    }
}

我不知道确切的代码,但是我很确定EPPlus( http://epplus.codeplex.com/或通过nuget)将能够执行您想要的操作。 尽管知道可以,但我从未真正使用它来加载excel文件,但是您可以从其他工作表中复制工作表。

EPPlus不需要像interop一样在计算机上安装Excel,并且清理也不像C#库那样多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM