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

时间:2014-09-14 12:51:30

标签: c# excel

我有4列4行的Excel表格。当我使用Count读取列{和行Microsoft.Office.Interop.Excel.WorkSheet时,对于行和列16384,行数和列数为1048576.对于行,计数必须为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();
            }

2 个答案:

答案 0 :(得分:3)

您已在页面上省略了UsedRange属性,正确使用的列数或行数:

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

答案 1 :(得分:0)

还有另外一件事,行和列以1而不是0开头,因此您需要将for循环范围设置为<=以获取所有数据,而不仅仅是<< / p>