【发布时间】:2018-10-08 04:17:39
【问题描述】:
我有一个用 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";'导致文件被保存并且工作簿包含一张名为“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>
谢谢
【问题讨论】:
-
什么是空?是单子吗?是sheet.Cells吗?是 sheet.Cells[1,1] 吗?
-
这很奇怪——你的代码对我来说很完美,所以代码本身不是问题。我的项目文件中的引用是 "
" 跨度> -
不应该是
Cells[1,"A"]吗? -
我相信它是 'sheet.Cells[1,1]' 为空,因为我可以引用 'sheet.Name' 并更改它,还可以得到 'sheet.Cells.Count'返回值 0。
-
您是否尝试过让应用程序可见 (excel.Visible = true;) 以查看工作表的外观以及是否可以手动输入单元格 A1。我的另一个想法可能是权限问题-您可能无权在根目录中创建文件-尝试在您知道您具有写入权限的文件夹中创建它(例如 Environment.SpecialFolder.MyDocuments)
标签: c# excel visual-studio-code excel-interop .net-core-2.0