Read data in Excel files using C#

MS Excel files are widely used to store data in the form of rows and columns. In various cases, the large datasets are also maintained in Excel files. Often, you have to read Excel files and fetch data from within your .NET applications. To achieve that within a few simple steps, this article shows how to read an Excel file in C#. Particularly, it covers how to read a whole Excel file or only a single worksheet from it.

C# Library to Read Excel Files

To read data from the worksheets, we will use Aspose.Cells for .NET. It is a powerful and feature-rich API to create and manipulate Excel files. Moreover, it allows you to read Excel files quite easily. The API can be downloaded from the downloads section or installed via NuGet.

PM> Install-Package Aspose.Cells

Read an Excel File in C#

In Excel files, the data is stored inside cells where each cell is identified by its name (A1, B3, etc.) or the row and column index. The collection of cells makes a worksheet and an Excel file may contain single or multiple worksheets. Finally, all the worksheets collectively form a workbook. Aspose.Cells for .NET uses the same naming conventions to manipulate Excel files.

The following are the steps to read an Excel file and print its data using C#.

  • Load the Excel file using Workbook class.
  • Create an object of WorksheetCollection class and get reference of the worksheets using Workbook.Worksheets.
  • Start a loop to go though all the worksheets in the collection and in each iteration, perform the following steps:
    • Get reference of the worksheet in a Worksheet object.
    • Get count of data rows and columns in the worksheet.
    • Start a loop for rows.
    • Start a nested loop for columns.
    • Read data from each cell using Worksheet.Cells[i, j].Value property.

The following code sample shows how to read an Excel file in C#.

The following is the output that we get in the console after running the code sample above.

Reading data in the worksheets of Excel file in C#

Reading an Excel File in C#

Read a Particular Worksheet in Excel in C#

You can also read only a particular worksheet in the Excel file by following the steps below.

The following code sample shows how to read data from a particular worksheet in C#.

Get a Free API License

You can use Aspose.Cells for .NET without evaluation limitations by getting a free temporary license.

Conclusion

In this article, you have learned how to read Excel files dynamically in C#. With the help of code samples, you have seen how to read data from a particular worksheet or all the worksheets in an Excel workbook. In addition, you can explore other features of Aspose.Cells for .NET using the documentation. In case you would have any queries, feel free to let us know via our forum.

See Also