如何将多个 excel 文件合并为一个 excel 文件
本文关键字:excel 文件 一个 合并 | 更新日期: 2023-09-27 18:32:58
所以我试图制作一个 excel 工作表聚合器。在我的工作中,我们会有人向我们发送一堆单独的 excel 文件,这些文件都相关,每个文件只使用 1 张纸。
我在某种程度上遵循了上一篇文章的想法。但是在这样做之后,我复制的一些 excel 工作表出现空白。只有某些。我不知道为什么有些是空白的,而另一些是好的。
这是我用来打开和复制 excel 文件的代码
OpenFileDialog browse = new OpenFileDialog();
browse.Multiselect = true;
DialogResult result = browse.ShowDialog();
if (result == DialogResult.OK)
try //try to open it. If its a proper excel file
{
excel = new Excel.Application();
excel.Workbooks.Add("");
finalized = excel.Workbooks[1];
excel.SheetsInNewWorkbook = 1;
for(int i=0; i< browse.FileNames.Length; i++)
{
excel.Workbooks.Add(browse.FileNames[i]);
}
//skip the first workbook as it is the finalized one
//also note everything in excel starts at 1 and not 0
for(int i=2; i<excel.Workbooks.Count; i++)
{
int count = excel.Workbooks[i].Worksheets.Count;
excel.Workbooks[i].Activate();
for (int j = 1; j < count; j++)
{
Excel._Worksheet pastee = (Excel._Worksheet)excel.Workbooks[i].Worksheets[j];
Excel._Worksheet sheet = (Excel._Worksheet)finalized.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//Excel._Worksheet sheet = finalized.Sheets[1];
pastee.Copy(Before: sheet);
}//end of for j
}//end of for i
}//end of try
这是我用来保存 excel 文件的代码
SaveFileDialog browse = new SaveFileDialog();
browse.Title = "Save as Excel";
browse.Filter = "Excel workbook | *.xlsx";
DialogResult result = browse.ShowDialog();
finalized.SaveAs(browse.FileName, Excel.XlFileFormat.xlWorkbookDefault);
MessageBox.Show("Success", "Message");
//unlock the file
Global.releaseComObjects(finalized, excel);
在内部循环中,您将一个新工作表添加到"最终"工作簿("工作表")中,并为每个源工作表复制一个工作表。因此,由Add
命令创建的每个"工作表"都将是空的,因为实际上您为每个源工作表创建了两个工作表。另一个问题是,正如您提到的,excel 中的数组是基于 1 的;所以你必须循环直到j <= count
不j < count
.
所以我认为代码会更好:
Excel.Worksheet dummy = finalized.Worksheets[1];
for (int i = 2; i <= excel.Workbooks.Count; i++)
{
int count = excel.Workbooks[i].Worksheets.Count;
for (int j = 1; j <= count; j++)
{
Excel._Worksheet pastee = (Excel._Worksheet)excel.Workbooks[i].Worksheets[j];
pastee.Copy(dummy);
}
}
dummy.Delete();
将工作表合并为一个的最简单方法是通过名为 Spire.Xls 的第三部分组件。它是一个独立的 .NET 组件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Xls;
using System.Data;
namespace Spire.XLS
{
class Program
{
static void Main(string[] args)
{
Workbook workbook = new Workbook();
//load the first workbook
workbook.LoadFromFile(@"merge1.xlsx");
//load the second workbook
Workbook workbook2 = new Workbook();
workbook2.LoadFromFile(@"merge2.xlsx");
//import the second workbook's worksheet into the first workbook using a datatable
Worksheet sheet2 = workbook2.Worksheets[0];
DataTable dataTable = sheet2.ExportDataTable();
Worksheet sheet1 = workbook.Worksheets[0];
sheet1.InsertDataTable(dataTable, false, sheet1.LastRow + 1, 1);
//save the workbook
workbook.SaveToFile("result.xlsx");
}
}
}