gpt4 book ai didi

c# - (Excel 互操作)如何将一个工作表复制到 VSTO 中的另一个工作簿?

转载 作者:太空宇宙 更新时间:2023-11-03 14:57:55 25 4
gpt4 key购买 nike

我在网上搜索了很多,但不幸的是,没有一个有效。 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";

关于c# - (Excel 互操作)如何将一个工作表复制到 VSTO 中的另一个工作簿?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48017195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com