[英]Writing values to Excel cells using C#
我有一個用 Visual Studio Code 編寫的簡單 C# 方法,它應該創建一個新的 Excel 工作簿,將值寫入工作表中的單元格,然后保存文件。
using System;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
namespace Test
{
class ExcelTest
{
public void TestMethod()
{
String outputPath = "C:\\Test.xlsx";
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Add(Type.Missing);
Excel.Worksheet sheet = (Excel.Worksheet)workbook.ActiveSheet;
((Excel.Range)sheet.Cells[1,1]).Value = "Hello";
workbook.SaveAs(outputPath);
workbook.Close();
excel.Quit();
}
}
}
調用此方法時,代碼執行停止在 ((Excel.Range)sheet.Cells[1,1]).Value = "Hello"; 行,但有以下例外:
發生異常:CLR/System.NullReferenceException 發生類型為“System.NullReferenceException”的未處理異常:“未將對象引用設置為對象的實例。”
該方法似乎正在與 Excel 交互,因為將行替換為 'sheet.Name = "Test";' 導致文件被保存,工作簿包含一張名為“測試”的工作表。
作為參考,我使用的是 Visual Studio Code,並在我的機器上安裝了 Excel 2016,並且 .csproj 文件具有以下引用:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Office.Interop.Excel" Version="*"/>
</ItemGroup>
</Project>
謝謝
作為參考,我通過將應用程序重建為 .NET Framework 應用程序而不是 .NET Core 應用程序來解決此問題。 執行此操作后,COM 互操作功能起作用了。
你有沒有試過:
sheet.Cells[1,1].Value = "Hello";
我認為不需要將其轉換為范圍對象來設置值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.