在这里,我尝试使用下面提到的代码(Spire.Xls dll)将两个Excel文件合并到一个Excel工作表中。
这是两个excel合并的代码。
workbook = new Workbook();
//load the first workbook
workbook.LoadFromFile(ArrayExcelFiles[0]);
//load the second workbook
Workbook workbook2 = new Workbook();
workbook2.LoadFromFile(ArrayExcelFiles[1]);
//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);
workbook.SaveToFile(OutputPath + "Merged.xls", ExcelVersion.Version2007);
但是问题是,当尝试使用相同的逻辑合并三个excel文件时,输出与两个合并的excel输出相同,第三个excel没有合并。
这是三个excel文件的代码。
Workbook workbook1 = new Workbook();
//load the first workbook
workbook1.LoadFromFile(ArrayExcelFiles[0]);
//load the second workbook
Workbook workbook2 = new Workbook();
workbook2.LoadFromFile(ArrayExcelFiles[1]);
//load the third workbook
Workbook workbook3 = new Workbook();
workbook3.LoadFromFile(ArrayExcelFiles[2]);
//import the second workbook's worksheet into the first workbook using a datatable
Worksheet sheet3 = workbook3.Worksheets[0];
DataTable dataTable = sheet3.ExportDataTable();
Worksheet sheet2 = workbook2.Worksheets[0];
dataTable = sheet2.ExportDataTable();
Worksheet sheet1 = workbook1.Worksheets[0];
sheet1.InsertDataTable(dataTable, false, sheet1.LastRow + 1, 1);
workbook1.SaveToFile(OutputPath + "Merged.xls", ExcelVersion.Version2007);
答案 0 :(得分:1)
在第二个示例中,您没有使用相同的逻辑,因此它不起作用。在第二个代码上尝试类似的操作或对其进行一些更改:
//import the second workbook's worksheet into the first workbook using a datatable
Worksheet sheet3 = workbook3.Worksheets[0];
Worksheet sheet2 = workbook2.Worksheets[0];
DataTable dataTable2 = sheet2.ExportDataTable();
Worksheet sheet1 = workbook1.Worksheets[0];
DataTable dataTable1 = sheet1.ExportDataTable();
sheet3.InsertDataTable(dataTable2, false, sheet3.LastRow + 1, 1)
sheet3.InsertDataTable(dataTable1, false, sheet3.LastRow + 1, 1)
上面的代码使用sheet3
并向其中插入2个数据表-一个来自sheet2
的数据表,另一个来自sheet1
的数据表。
答案 1 :(得分:1)
您只能插入workbook2
中的工作表,因此并不奇怪。您从datatable
获得了workbook3
,但是在对它进行任何其他操作之前,立即用workbook2
中的数据覆盖了它。您不能在一个DataTable
对象中存储两个表。最后一个简单地替换了第一个(就像其他变量赋值一样)。
您需要使用两个单独的数据表运行两个单独的insertDataTable
命令,每个工作表中一个:
//import the second and third workbooks' worksheets into the first workbook using a datatable
Worksheet sheet2 = workbook2.Worksheets[0];
DataTable dataTable = sheet2.ExportDataTable();
Worksheet sheet3 = workbook3.Worksheets[0];
DataTable dataTable2 = sheet3.ExportDataTable();
Worksheet sheet1 = workbook1.Worksheets[0];
sheet1.InsertDataTable(dataTable, false, sheet1.LastRow + 1, 1);
sheet1.InsertDataTable(dataTable2, false, sheet1.LastRow + 1, 1);
workbook1.SaveToFile(OutputPath + "Merged.xls", ExcelVersion.Version2007);
当然可以通过使用循环等使代码变得更加整洁,减少重复,但这是基本的解决方案。