c#:将excel工作簿复制到另一个工作簿

时间:2013-04-18 15:42:22

标签: c# excel excel-2010

我已编写代码以将工作表的副本提供给新的excel文件。下面是我的C#代码,问题是缺少一些命名的单元格,我在Excel-2010中检查了这个。

C#代码:

string strPath=@"C:\NewFolder\somexcelfile.xls";
Excel.Workbook souWorkbook = xCel.Workbooks.Open(strPath);
Excel.Workbook destWorkbook = xCel.Workbooks.Add();

foreach (Excel.Worksheet wkSheet in souWorkbook.Worksheets)
{
   wkSheet.Copy(destWorkbook.Worksheets[1]);
}
destWorkbook.SaveCopyAs("C:\NewFolder\copy.xls");

1 个答案:

答案 0 :(得分:0)

如果您需要复制指定的单元格,可以使用以下代码示例

Sub Copy_All_Defined_Names()
   ' Loop through all of the defined names in the active
   ' workbook.
     For Each x In ActiveWorkbook.Names
      ' Add each defined name from the active workbook to
      ' the target workbook ("Book2.xls" or "Book2.xlsm").
      ' "x.value" refers to the cell references the
      ' defined name points to.
      Workbooks("Book2.xls").Names.Add Name:=x.Name, _
         RefersTo:=x.Value
   Next x
End Sub