[英]c#: Accessing cells in excel worksheet throws NullReferenceException
所以我一直在嘗試編寫一個控制台應用程序(.Net Core),它從 Excel 文件中讀取數據,但我有點卡住了。
我一直試圖讓這個代碼示例工作: https://www.csharp-console-examples.com/general/reading-excel-file-in-c-console-application/
我需要顯式使用(Range)cell
,因為當示例代碼嘗試直接訪問單元格時,Visual Studio 會拋出錯誤。
嘗試為工作表和范圍加載工作表和使用的范圍m_ObjectToDataMap = null
時。 由於 System.NullReferenceException,使用 excelRange.Rows 訪問行失敗:“對象引用未設置為 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();
}
我嘗試了很多不同的代碼,循環遍歷所有工作表或通過其名稱調用工作表,但它總是以工作表和范圍加載不正確以及 NullReferenceException 結束。
任何幫助,將不勝感激。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.