[英]unable to cast COM object of type 'microsoft.Office.Interop.Excel.ApplicationClass' to 'microsoft.Office.Interop.Excel.Application'"
[英]Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.WorksheetClass'
我正在嘗試從一堆聚合數據中創建並在C#中保存新的Excel文檔。 現在,我只是試圖讓基礎知識工作到編輯表格單元格等等。這是我只是嘗試設置一個單元格的內容:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
namespace DebugReport
{
class MonumentDebugReport
{
static void Main(string[] args)
{
Worksheet spreadsheet = new Worksheet();
spreadsheet.Cells[0, 0] = "stuff";
}
}
}
返回:
無法將“Microsoft.Office.Interop.Excel.WorksheetClass”類型的COM對象強制轉換為接口類型“Microsoft.Office.Interop.Excel._Worksheet”。 此操作失敗,因為由於以下錯誤,對IID為“{000208D8-0000-0000-C000-000000000046}”的接口的COM組件的QueryInterface調用失敗:不支持此類接口(HRESULT異常:0x80004002(E_NOINTERFACE)) 。
在我設置單元格的行上。 對我來說,這看起來與我見過的大多數示例/教程完全一樣,而且我在C#文檔中找不到任何表明這不起作用的內容。
就像漢斯已經說過你需要首先創建一個Excel應用程序,然后你添加一個工作簿,然后你添加一個工作表( 或嘗試訪問已經存在的Sheets[1]
)
using Microsoft.Office.Interop.Excel
和別名
using Excel = Microsoft.Office.Interop.Excel
然后
Excel.Application xlApp = new Excel.Application();
xlApp.Visible = true;
Excel.Workbook xlWb = xlApp.Workbooks.Add() as Excel.Workbook;
Excel.Worksheet xlSheet = xlWb.Sheets[1] as Excel.Worksheet;
Excel.Range range = xlSheet.get_Range("A1");
range.Value = "hello world!";
然后看看如何正確清理Excel互操作對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.