So I've been trying to write a console application (.Net Core) which reads data from an Excel file but I'm kinda stuck.
I've been trying to get this code sample to work: https://www.csharp-console-examples.com/general/reading-excel-file-in-c-console-application/
I needed to use (Range)cell
explicitly because Visual Studio threw errors when the sample code tried to access the cell directly.
When trying to load the worksheet and the used range m_ObjectToDataMap = null
for both worksheet and range. Accessing the rows with excelRange.Rows fails due to System.NullReferenceException: 'Object reference not set to an instance of an object.'
static void Main(string[] args)
{
//Create COM Objects.
Application excelApp = new Application();
if (excelApp == null)
{
Console.WriteLine("Excel is not installed!!");
return;
}
Workbook excelBook = excelApp.Workbooks.Open(@"D:\test.xlsx");
_Worksheet excelSheet = (_Worksheet)excelBook.Sheets[1];
Range excelRange = excelSheet.UsedRange;
foreach (Range row in excelRange.Rows) // Here is the NullReference Error
{
// create new line
Console.Write("\r\n");
foreach (Range col in excelRange.Columns)
{
Range cell = (Range)excelRange.Cells[row, col];
// write the console
if (excelRange.Cells[row, col] != null && cell.Value2 != null)
Console.Write(cell.Value2.ToString() + "\t");
}
}
//after reading, relaase the excel project
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
Console.ReadLine();
}
I tried a lot of different code, looping through all sheets or calling the sheet by its name but it always ends with worksheet and range being loaded incorrectly and the NullReferenceException.
Any help would be appreciated.