Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read All Rows and Columns Using Microsoft.Office.Interop.Excel

Tags:

c#

excel

I have excel sheet with 4 columns and 4 rows. When I read the columns and rows Count with Microsoft.Office.Interop.Excel.WorkSheet the count of rows and columns are 1048576 for rows and for columns 16384. The count must be 4 for rows and 4 for columns. What did I miss ?

            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();
            }
like image 863
theChampion Avatar asked Sep 14 '14 12:09

theChampion


People also ask

How do I use Microsoft Office Interop Excel in .NET core?

Office. Interop. Excel' nuget package, and then add reference to 'Microsoft Excel 16.0 Object Library' (right click the project -> 'Add' -> 'Reference' -> search and add 'Microsoft Excel 16.0 Object Library' ). Click ''Interop.

What is Excel range in C#?

Excel. Range that contains a single cell, an entire column, an entire row, or it can be a string that names a single cell in the language of the application.


1 Answers

You have omitted UsedRange property, the correct used column or row count on your sheet you get like this:

  int totalColumns = mySheet.UsedRange.Columns.Count;
  int totalRows = mySheet.UsedRange.Rows.Count;
like image 96
Vojtěch Dohnal Avatar answered Oct 23 '22 05:10

Vojtěch Dohnal