我有4列4行的Excel工作表。当我读取带有Count的列和行Microsoft.Office.Interop.Excel.WorkSheet时,行和列16384的行和列计数为1048576。行和列的计数必须为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;

08-08 08:56