使用 C# 将值写入 Excel 个单元格

Writing values to Excel cells using C#

我有一个用 Visual Studio 代码编写的简单 C# 方法,应该创建一个新的 Excel 工作簿,将值写入工作中的单元格 sheet 然后保存文件.

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";符合以下例外情况:

Exception has occurred: CLR/System.NullReferenceException An unhandled exception of type 'System.NullReferenceException' occurred: 'Object reference not set to an instance of an object.'

该方法似乎与 Excel 交互,因为用 'sheet.Name = "Test";' 替换该行会导致文件被保存并且工作簿包含一个 sheet,名称为 'Test'.

作为参考,我正在使用 Visual Studio 代码,并在我的机器上安装了 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>

谢谢

你试过了吗:

sheet.Cells[1,1].Value = "Hello";

我认为不需要将其转换为范围对象来设置值。

作为参考,我通过将应用程序重建为 .NET Framework 应用程序而不是 .NET Core 应用程序来修复此问题。 COM 互操作功能在执行此操作后起作用。