如何将工作表从多个工作簿合并到新工作簿中

时间:2018-12-11 16:28:13

标签: c# excel excel-interop

我想合并来自多个工作簿的多个工作表的数据。 例如,我有多个带有多个工作表的工作簿。

因此,请考虑我要合并“ WorkBook1”的“ Worksheet1”中的数据和“ Workbook2”的“ Worksheet2”中的数据,并分别合并到新“ WorkBook”的“ NewWorkSheet”中。我想这样做的方式是,将数据插入到另一个下面的“ NewWorkSheet”中,如“ Worksheet1”中的前20行,然后 接下来是“ Worksheet2”中的20个,依此类推...

我只能从一个工作表合并到一个新工作表,而不能从其他工作表合并到新工作表。

Workbook xlWorkbookDLA3 = xlApp.Workbooks.Open(dropBoxPath + "Week49DLA3.xlsm");
Worksheet worksheetDLA3 = xlWorkbookDLA3.Worksheets["Wed-A"];

Workbook xlWorkbookDLA4 = xlApp.Workbooks.Open(dropBoxPath + "Week49DLA4.xlsm");
Worksheet worksheetDLA4 = xlWorkbookDLA4.Worksheets["Thurs-A"];

Workbook destionationworkBook = xlApp.Workbooks.Open(dropBoxPath + "Test.xlsm");
Worksheet destworkSheet = destionationworkBook.Worksheets["Sheet2"];

Microsoft.Office.Interop.Excel.Range from, to;


from = worksheetDLA3.Range["B7:S7"].EntireColumn;
to = destworkSheet.Range["B7:S7"].EntireColumn;

from.Copy(to);


destionationworkBook.SaveAs(@"C:\Users\ashish.mokadam\Desktop\DropBox\Test" + ".xlsm");

1 个答案:

答案 0 :(得分:2)

对于每个您希望从其复制 的工作表(请注意,对于第一个工作表,),请在“ from.Copy(to);之间插入以下代码示例; ”和“ destionationworkBook.SaveAs(...”:

     var destination_start_row = destworkSheet.UsedRange.Rows.Count + 1;  // + 1 because Excel is 1-indexed
     var source_used_rows      = worksheetDLA4.UsedRange.Rows.Count;

     from = worksheetDLA4.Range["B1:S" + source_used_rows];
     to   = destworkSheet.Range["B" + destination_start_row + ":S" + destination_start_row + source_used_rows];
     from.Copy(to);

问题是您试图将整个列从源工作表复制到目标工作表,从而覆盖目标工作表中的值。此代码仅复制一定范围的单元格,而不复制整个数据列。

此外,您的变量名“ desti o nationworkBook”中有一个错字。它应该是“ destinationworkBook”。