我在网上搜索了很多,但不幸的是,没有一个有效。 How to copy sheets from a workbook to another workbook , Cutting and Pasting Cell Values in Excel using C# , Error: Pastespecial method of range class failed .
问题是,如果我在同一个工作簿中创建工作表,代码就可以正常工作。但是,如果我创建了一个新工作簿,那么粘贴将不起作用。
//copy function: copy to a new worksheet in the same workbook
var copyFromRange = oldSheet.Range[
(Excel.Range)oldSheet.Cells[1, 1],
oldSheet.Cells[firstPackageStartLine - 1, lastColIgnoreFormulas]];
copyFromRange.Copy(Type.Missing);
var copyHeaderRange = newSheet.Range[(Excel.Range)newSheet.Cells[1, 1], newSheet.Cells[firstPackageStartLine - 1, lastColIgnoreFormulas]];
copyHeaderRange.PasteSpecial(Excel.XlPasteType.xlPasteAll, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);
//Copy to a new workbook, won't work
var excel = new Excel.Application();
var newWorkbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
var newSheet = (Excel.Worksheet)newWorkbook.Worksheets.Add();
newSheet.Name = "sheetName";
//copy function, same as above. But this won't work, PasteSpecial would throw null reference error.
//If I changed the copyHeaderRange to below, then it will throw: PasteSpecial method of Range class failed.
var copyHeaderRange = (Excel.Range)newSheet.Cells[1, 1];
//If the copyRange is defined as below, it will throw null reference error while pastespecial
var copyHeaderRange = newSheet.Range[(Excel.Range)newSheet.Cells[1, 1], newSheet.Cells[firstPackageStartLine - 1, lastColIgnoreFormulas]];
我也试过打开一个新工作簿而不是开始一个新工作簿,但行不通。尝试在复制前激活工作表,也不起作用。
知道为什么会这样吗?
如果复制范围内有任何合并的单元格——即使它们没有超出该范围的坐标单元格——并且你正在创建 Excel Application 类的新实例,我认为这个错误是预料之中的。
除了新建
您的 excel
实例,您能否修改以使用相同的 Excel 实例(未测试):
var newWorkbook = oldSheet.Application.Workbooks.Add(System.Reflection.Missing.Value);
var newSheet = (Excel.Worksheet)newWorkbook.Worksheets.Add();
newSheet.Name = "sheetName";
我是一名优秀的程序员,十分优秀!