使用Microsoft.Office.Interop.Excel阅读所有行和列

我有4列4行excel表。 当我使用Microsoft.Office.Interop.Excel.WorkSheet读取列和行Count时,行和列的行数和列数分别为1048576和列16384.列数必须为4,列数为4。 我错过了什么 ?

  ApplicationClass excelApp = null; Workbook myWorkBook = null; Worksheet mySheet = null; Range dataRange = null; excelApp = new ApplicationClass(); myWorkBook = excelApp.Workbooks.Open(@"C:\Users\Dev2Admin\Desktop\Employees.xlsx"); mySheet = (Worksheet)myWorkBook.Sheets["Sheet1"]; for (int row = 1; row < mySheet.Rows.Count; row++) // Count is 1048576 instead of 4 { for (int col = 1; col < mySheet.Columns.Count; col++) // Count is 16384 instead of 4 { dataRange = (Range)mySheet.Cells[row, col]; Console.Write(String.Format(dataRange.Value2.ToString() + " ")); } Console.WriteLine(); } 

您已经省略了UsedRange属性,您的工作表中正确使用的列或行数就像这样:

  int totalColumns = mySheet.UsedRange.Columns.Count; int totalRows = mySheet.UsedRange.Rows.Count;