I have a simple C# method written in Visual Studio Code that should create a new Excel workbook, write a value to a cell within a worksheet and then save the file.
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();
}
}
}
When calling this method, code execution stops on the ((Excel.Range)sheet.Cells[1,1]).Value = "Hello"; line with the following exception:
Exception has occurred: CLR/System.NullReferenceException An unhandled exception of type 'System.NullReferenceException' occurred: 'Object reference not set to an instance of an object.'
The method seems to be interacting with Excel as replacing the line with 'sheet.Name = "Test";' results in the file being saved and the workbook containing one sheet with the name 'Test'.
For reference I am using Visual Studio Code, and have Excel 2016 installed on my machine, and the .csproj file has the following references:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Office.Interop.Excel" Version="*"/>
</ItemGroup>
</Project>
Thanks
Cells[1,"A"]? - CornelC