简体   繁体   English

C#Excel:从其他工作簿复制工作表时出现问题

[英]C# Excel: Issue in copying worksheet from different workbook

I'm currently trying to copy a worksheet from a different workbook which i succeed by using Copy() and PasteSpecial(). 我目前正在尝试从另一个工作簿复制工作表,该工作簿通过使用Copy()和PasteSpecial()成功完成。 However, I would like to know why the following code does not work even though many solutions online seems to use this approach. 但是,我想知道为什么即使许多在线解决方案似乎都使​​用这种方法,下面的代码也不起作用。

 Workbook currBook = Globals.ThisAddIn.GetActiveWorkbook(); Workbook copyBook = Globals.ThisAddIn.OpenWorkbook(Globals.ThisAddIn.Application.ActiveWorkbook.Path + @"\\copyFile.xlsm", true, true); //required worksheet Worksheet copySheet = Globals.ThisAddIn.GetWorksheet(copyBook, "ToCopy"); copySheet.Copy(currBook.Worksheets[1]); //close workbook copyBook.Close(); 

Function used to get specific sheet: 用于获取特定工作表的函数:

 public Excel.Worksheet GetWorksheet(Excel.Workbook book, string sheetName, bool create = false) { foreach (Excel.Worksheet sheet in book.Worksheets) { //worksheet with name found if (sheet.Name == sheetName) { sheet.Activate(); return sheet; } } //worksheet can't be found if (create) { Excel.Worksheet sheet = book.Worksheets.Add(); sheet.Name = sheetName; sheet.Activate(); return sheet; } return null; } 

There is no error from the stated code and the worksheet has been tested to exist. 声明的代码没有错误,并且工作表已经过测试。 The program simply does not create a copy into currBook 该程序根本不会在currBook中创建副本

Interestingly, I was just working on something else where this came up... 有趣的是,我只是在做其他事情而已。

In order to specify a destination it's necessary to use Range.Copy , not Sheet.Copy : 为了指定目的地,必须使用Range.Copy ,而不是Sheet.Copy

copySheet.UsedRange.Copy(currBook.Worksheets[1].Range["A1"]); 

If a destination can't be specified, then Excel puts the data in a new workbook. 如果无法指定目标,则Excel会将数据放入新的工作簿中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM