gpt4 book ai didi

C# Excel 类型转换

转载 作者:行者123 更新时间:2023-12-04 20:45:27 24 4
gpt4 key购买 nike

我有一个使用 Microsoft.Office.Interop.Excel.WorkbookClass 创建 Excel 电子表格的现有项目。我正在尝试将工作簿对象转换为 Microsoft.Office.Tools.Excel.Workbook ,但我收到一个异常,说明:

"Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.WorkbookClass' to class type 'Microsoft.Office.Tools.Excel.Workbook'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface."


Microsoft.Office.Interop.Excel.Application xlApp = null;
Microsoft.Office.Tools.Excel.Workbook xlWorkbook = null;
Microsoft.Office.Interop.Excel.Sheets xlSheets = null;
Microsoft.Office.Tools.Excel.Worksheet xlNewSheet = null;

xlApp = new Interop.Application();
xlApp.Visible = true;
xlWorkbook = (Microsoft.Office.Tools.Excel.Workbook)xlApp.Workbooks.Add(Interop.XlWBATemplate.xlWBATWorksheet);
xlSheets = xlWorkbook.Sheets as Interop.Sheets;
xlNewSheet = (Microsoft.Office.Tools.Excel.Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
xlNewSheet.Name = "SheetName1";

如果没有,这可能吗,我可以采取哪些其他选项,因为已经使用互操作类创建了 excel 工作表,并且

最佳答案

如果可能,请尽量避免使用 Visual Studio Tools For Office 内部的 Microsoft.Office.Tools 程序集。

我已将您的代码修改如下:

    Microsoft.Office.Interop.Excel.Application xlApp = null;
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = null;
Microsoft.Office.Interop.Excel.Sheets xlSheets = null;
Microsoft.Office.Interop.Excel.Worksheet xlNewSheet = null;

xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = true;
xlWorkbook = xlApp.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
xlSheets = xlWorkbook.Sheets as Microsoft.Office.Interop.Excel.Sheets;
xlNewSheet = xlSheets.Add(xlSheets[1], System.Type.Missing, System.Type.Missing, System.Type.Missing);
xlNewSheet.Name = "SheetName1";

关于C# Excel 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18706558/

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