[英]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.