How to Read Excel File in C#
Tags: csharp, ironxl, readexcelfile
Published: 2021-11-18 05:42:18

##How to read an Excel file in C#

1. Start a new C# project in Visual Studio (Console App, Windows Forms, etc.).
2. Use the NuGet Package Manager to install "IronXL.Excel".
3. Add necessary controls like labels and a DataGridView for displaying data.
4. Load the Excel workbook and select the worksheet to read.
5. Convert the worksheet data to a DataTable for easy manipulation and display.
6. Use IronXL to read various file formats, including XLS, XLSX, and CSV.


You might be thinking that reading excel files would be difficult and require high-level expertise, but this is not the case. I will show you that it only takes 2-3 lines of code with [IronXL](https://ironsoftware.com/csharp/excel/) to be able to read excel files.

##Introduction to IronXL:

IronXL is a .Net Library development brought to you by [Iron Software](https://ironsoftware.com/). This library provides excellent functions and APIs to help us read, create and update/edit our excel files and spreadsheets. IronXL does not require Excel to be installed on your server or Interop. Moreover, IronXL provides a faster and more intuitive API than Microsoft Office Interop Excel. 

IronXL works on .Net Core 2, Framework 4.5, Azure, Mono and, Mobile and Xamarin.
[![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zcgv0ryhkyqm1907bnun.png)](https://ironsoftware.com/csharp/excel/
)
##Creating an Example Project for our Demonstration

I will be using Windows Form App as an example, but you can use one of your choice, such as Asp.Net Web App, .Net core MVC or .Net Core web api. 

To create a new project, open Visual Studio, click on "Create New Project" => Select Template; I am using the Windows Form App, you can use any of your choosing. => Click on Next Button => Name Your Project; I have named mine as "C Sharp Read Excel File". => Click on Next = > Select your Target Framework; I am selecting .Net core 3.1, but again, you can choose your own. => Finally, click on "Create Project", and a project will be created and opened for you as shown below: 
![Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2i9wwdhtzcbgqrbeckj6.PNG)

Our next task is to Install the Nuget Package for IronXL.

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-9088905903067206"
     crossorigin="anonymous"></script>
<ins class="adsbygoogle"
     style="display:block; text-align:center;"
     data-ad-layout="in-article"
     data-ad-format="fluid"
     data-ad-client="ca-pub-9088905903067206"
     data-ad-slot="3029747192"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

##Adding the IronXL Nuget Package
We can add the IronXL Package in one of any three ways, so you can choose the method that suits you best. 

###Installing IronXL using the Package Manager Console
Open the Package Manager console in your Project and use the following command: 

Go to Tools => NuGet Package Manager => Package Manager Console.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/thq4l4vs8yia3k9iwtq8.PNG)
This will open the Package Manager console for you. Next, write the following command in the Package Manager console:

`PM > Install-Package IronXL.Excel`
###![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wetl4luo36zrd6oknn7q.PNG)
###Installing IronXL using the Nuget Package Manager
This is another way to install the Nuget Package Manager. If you have already completed installation using the previous method, than you won't need to use this one.

Go to:   Tools = > NuGet Package Manager => Manage NuGet Packages for Solution, and click on it. 

This will open the Nuget-Solution for you; click on "Browse" and search for IronXL.Excel in the search bar:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v64fp32p8bsdt8h11ywq.PNG)
Click on the "Install" button and it will install IronXL for you. After installing IronXL, go to your form and start designing it. 

###Downloading IronXL  
Another way of using IronXL is to download it directly from this [link](https://www.nuget.org/packages/IronXL.Excel). Once downloaded, just add the reference of the file in your project and start using it. 

##Design the Form
Now, we have to design the form to suit our requirements. I will use the minimum design for the demonstration. You can use any design depending on your needs. 

Go to the ToolBox=> Select Label (for name our example app), and select the "Panel and Data" grid view. Put the "Data" grid view inside the panel. Our design will look like the following:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kted7xiuaxfpkhjy97od.PNG)
Our form has now been designed. Our next task is to actually write the code for reading an excel file or excel sheet in C#.

##Write Code for Reading Excel Files in C#
We want our app to read any given excel file at the click of a button, so for this, double-click on the "Read Excel File" button, and the following code will appear:
```
private void button1_Click(object sender, EventArgs e)
        {
        }
```
Next, add the following namespace in this file:
```
using System;
using System.Windows.Forms;
using IronXL;
using System.Data;
```
Using the IronXL namespace is necessary to access the IronXL functions. However, you can use other namespaces as per the requirements of your own projects.
```
WorkBook workbook = WorkBook.Load("Weather.xlsx");
            WorkSheet sheet = workbook.GetWorkSheet("Sheet1");
            DataTable dt = sheet.ToDataTable(true);
            dataGridView1.DataSource = dt;
```
The first statement will load the excel workbook "Weather.xlsx" for us. I have chosen the xlsx file format as an example. You can choose any file of your choice.

After loading the excel workbook, we need to select the excel worksheet we want to read. After that, we need to convert our worksheet into a data table so that we can further load it into our Data Grid View. 

This will read the file for us and display all its data in the data grid view. 

####Output for Reading the Data from Excel File using C#:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yq6vr89ta8onb9qn28by.PNG)

Let's open our "Weather.xlsx" file in Microsoft Excel and compare our output. xlsx file is the extension for a Microsoft Excel file. 
####Excel File:
![Read Excel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y420i0lhgojd702jk2oo.PNG)
Now that we can read excel files using C#, let's explore some advanced options.

Let's suppose that you want to read the data from an excel file for a specific cell range. Let's look at how to do that.

##Read Data from Excel within a Specific Cell Range:
To read the data in a specific cell range, write the following code behind the button: 
```
WorkBook workbook = WorkBook.Load("Weather.xlsx");
            WorkSheet sheet = workbook.GetWorkSheet("Sheet1");
            var range = sheet["A1:C6"];
            DataTable dt = range.ToDataTable(true);
            dataGridView1.DataSource = dt;
```
The first two lines are the same as those for loading the workbook and selecting the worksheet we want to read. On the third line, we have selected the cell range within which we want to read the data. I have selected the range A1:C6 which means that it will read the first three columns: Column A, Column B, and Column C, as well as the first six rows, as shown below.

####Output for Read Data within a Specific Cell Range:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0mbfq9vq7j0ttx1sap99.PNG)

##Read XLS or XLSX File:
We can read excel files no matter whether the file format is xls or xlsx. In the previous example, we looked at the example of reading the data from an Xslx file. Next, let's look at saving the same file in .xls format and then reading it. The code will remain the same, we just have to change the file name to "Wather.xls" as shown below:

`WorkBook workbook = WorkBook.Load("Weather.xls");`
####Output for Reading XLS File:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9z82wil84udp9ud4j2e9.PNG)
##Read CSV File in C#:
If you have csv files instead of an excel file, you have to make slight changes to the code.
Let's look at the following example.
I have the same Weather file saved as "Weather.csv", so I am using the same file for all the examples. Again, you can use any example according to your requirements.
```
WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
            WorkSheet sheet = workbook.DefaultWorkSheet;
            DataTable dt = sheet.ToDataTable(true);
            dataGridView1.DataSource = dt;
```
On the first line will load the csv file for you and define the file format. The second line will select the worksheet, while the other two code lines are the same as those in the previous examples.
####Output for Reading CSV File
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gmw8pkbjsde57rirk4m9.PNG)
##Summary:
In this tutorial we have learned how to read data using excel in C# by selecting specific cells and ranges, or different file formats. This all was done with just a few lines of code.

If you want to learn more about Iron Software products, please click on this [link](https://ironsoftware.com/). If you decide that you’d like to try it out for yourself, then go ahead and take advantage of the Iron Software 30-day Free-Trial . You may also want to take a look at the Iron Suite, this complete package includes five .Net Libraries, this special offer means you can get all five products for the price of only two. For more information, please click [here](https://ironsoftware.com/suite/). 

I hope that you have found this guide helpful and easy to follow. If you need any further assistance, please feel free to post a comment.