[英]How to merge two Excel workbook into one workbook in C#?
Let us consider that I have two Excel files (Workbooks) in local.让我们考虑一下我在本地有两个 Excel 文件(工作簿)。 Each Excel workbook is having 3 worksheets.每个 Excel 工作簿都有 3 个工作表。
Lets say WorkBook1 is having Sheet1, Sheet2, Sheet3假设 WorkBook1 有 Sheet1、Sheet2、Sheet3
Workbook2 is having Sheet1, Sheet2, Sheet3. Workbook2 有 Sheet1、Sheet2、Sheet3。
So here I need to merge these two excel workbook into one and the new excel workbook that is let's say Workbook3 which will have total 6 worksheets (combination of workbook1 and workbook2).所以在这里我需要将这两个 excel 工作簿合并成一个新的 excel 工作簿,比如说 Workbook3,它将有总共 6 个工作表(workbook1 和 workbook2 的组合)。
I need the code that how to perform this operation in c# without using any third party tool.我需要如何在不使用任何第三方工具的情况下在 c# 中执行此操作的代码。 If the third party tool is free version then its fine.如果第三方工具是免费版本,那就没问题了。
An easier solution is to copy the worksheets themselves , and not their cells.一个更简单的解决方案是复制工作表本身,而不是它们的单元格。
This method takes any number of excel file paths and copy them into a new file:此方法采用任意数量的 excel 文件路径并将它们复制到一个新文件中:
private 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();
}
Edit: notice that you might want to Move
method instead of Copy
in case you have dependencies between the sheets, eg pivot table, charts, formulas, etc. Otherwise the data source will disconnect and any changes in one sheet won't effect the other.编辑:请注意,如果工作表之间存在依赖关系,例如数据透视表、图表、公式等,您可能希望使用Move
方法而不是Copy
。否则数据源将断开连接,并且一张工作表中的任何更改都不会影响另一张工作表.
There are generally two ways to automate Excel tasks with C#. 通常,有两种方法可以使用C#自动执行Excel任务。
Why would you ever go for a third party library when Microsoft offers its own library? 当Microsoft提供自己的库时,为什么还要去第三方库? I am glad you asked. 我很高兴你问。
That is why there is a plethora of third party libraries available. 这就是为什么有大量第三方库可用的原因。 Both paid and open-source. 付费和开源。 I generally dislike paying for stuff & have found the open-source, free ExcelMapper (for very simple scenarios) and EPPlus libraries really great to work with. 我通常不喜欢花钱买东西,并且发现开源,免费的ExcelMapper (对于非常简单的场景)和EPPlus库非常有用。
How to merge two Excel workbooks using EPPlus Here is the code: 如何使用EPPlus合并两个Excel工作簿这里是代码:
var file1 = new FileInfo(@"C:\Temp\Sample\Book 1.xlsx");
var file2 = new FileInfo(@"C:\Temp\Sample\Book 2.xlsx");
var mergedFileName = new FileInfo(@"C:\Temp\Sample\Merged.xlsx");
//lets open the file
using (var firstFile = new ExcelPackage(file1))
{
using (var secondFile = new ExcelPackage(file2))
{
foreach (var ws in secondFile.Workbook.Worksheets)
{
string worksheetName = ws.Name;
// if worksheet name already exists - change name
if (firstFile.Workbook.Worksheets.Any(ar => ar.Name == ws.Name))
worksheetName = string.Format("{0} - {1}", worksheetName, "Copy");
firstFile.Workbook.Worksheets.Add(worksheetName, ws);
}
}
firstFile.SaveAs(mergedFileName);
}
This is what it looks like when running the code: 这是运行代码时的样子: (source: excel-automation-guide.com ) (来源: excel-automation-guide.com )
System.Data.Odbc.OdbcDataAdapter Odbcda;
//CSV File
strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + SourceLocation + ";Extensions=asc,csv,tab,txt;Persist Security Info=False";
sqlSelect = "select * from [" + filename + "]";
System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection(strConnString.Trim());
conn.Open();
Odbcda = new System.Data.Odbc.OdbcDataAdapter(sqlSelect, conn);
Odbcda.Fill(ds, DataTable);
conn.Close();
Here's a working sample that joins two books into a new one, hope it will give you an idea:这是一个将两本书合并成一本新书的工作示例,希望它能给你一个想法:
using System;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
namespace MergeWorkBooks
{
class Program
{
static void Main(string[] args)
{
Excel.Application app = new Excel.Application();
app.Visible = true;
app.Workbooks.Add("");
app.Workbooks.Add(@"c:\MyWork\WorkBook1.xls");
app.Workbooks.Add(@"c:\MyWork\WorkBook2.xls");
for (int i = 2; i <= app.Workbooks.Count; i++)
{
int count = app.Workbooks[i].Worksheets.Count;
app.Workbooks[i].Activate();
for (int j=1; j <= count; j++)
{
Excel._Worksheet ws = (Excel._Worksheet)app.Workbooks[i].Worksheets[j];
ws.Select(Type.Missing);
ws.Cells.Select();
Excel.Range sel = (Excel.Range)app.Selection;
sel.Copy(Type.Missing);
Excel._Worksheet sheet = (Excel._Worksheet)app.Workbooks[1].Worksheets.Add(
Type.Missing, Type.Missing, Type.Missing, Type.Missing
);
sheet.Paste(Type.Missing, Type.Missing);
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.