Book Online or Call 1-855-SAUSALITO

Sign In  |  Register  |  About Sausalito  |  Contact Us

Sausalito, CA
September 01, 2020 1:41pm
7-Day Forecast | Traffic
  • Search Hotels in Sausalito

  • CHECK-IN:
  • CHECK-OUT:
  • ROOMS:

C# Read Excel File with Examples

Photo from Unsplash

Originally Posted On: https://ironsoftware.com/csharp/excel/tutorials/how-to-read-excel-file-csharp/

 

This tutorial explains how to read an Excel file in C# and using libraries for everyday tasks like validation, conversion to a database, saving data from Web APIs, and modifying formulae within the spreadsheet. This article references the IronXL code samples, which is a .NET Core Console App.

Reading and creating Excel files in C# and all other .NET languages is easy using the IronXL software library.

It does not require Excel to be installed on your server or Interop. IronXL provides a faster and more intuitive API than Microsoft.Office.Interop.Excel.

OverviewRead Excel files in C# by following these steps (CSV XLSX & XLS)
  1. Download the Read CSV Excel File C# Library
  2. Load and read an Excel file (workbook)
  3. Create an Excel workbook in CSV or XLSX
  4. Enable cells and edit cell values in
  5. Validate spreadsheet data
  6. Export data using Entity Framework
Read Data from Excel file using IronXL

IronXL is a .NET library that facilitates reading and editing Microsoft Excel documents with C#. This tutorial will walk you through using C sharp code to read the Excel file.

  1. Install the IronXL Excel Library. We can do this using our NuGet package or by downloading the .Net Excel DLL.
  2. Use the WorkBook.Load method to read any XLS, XLSX or CSV document.
  3. Get Cell values using intuitive syntax: sheet[“A11”].DecimalValue
IronXL Includes:
  • Dedicated product support from our .NET engineers
  • Easy installation via Microsoft Visual Studio
  • 30 day free trial test for development. Licenses from $399.

We will see how easy it is to read Excel files in C# or VB.Net using the IronXL library. The samples contain three Excel sheets.

 

 

Read XLS or XLSX Files: Quick Code

In this example we can see how to read the excel file efficiently without Interop in C#. The final Advanced Operations show Linq compatibility and aggregate range mathematics.

  1. /**
  2. Read XLS or XLSX File
  3. anchor-read-an-xls-or-xlsx-file
  4. **/
  5. using IronXL;
  6. using System.Linq;
  7. //Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
  8. WorkBook workbook = WorkBook.Load(“test.xlsx”);
  9. WorkSheet sheet = workbook.WorkSheets.First();
  10. //Select cells easily in Excel notation and return the calculated value
  11. int cellValue = sheet[“A2”].IntValue;
  12. // Read from Ranges of cells elegantly.
  13. foreach (var cell in sheet[“A2:A10”])
  14. {
  15. Console.WriteLine(“Cell {0} has value ‘{1}'”, cell.AddressString, cell.Text);
  16. }
  17. ///Advanced Operations
  18. //Calculate aggregate values such as Min, Max and Sum
  19. decimal sum = sheet[“A2:A10”].Sum();
  20. //Linq compatible
  21. decimal max = sheet[“A2:A10”].Max(c => c.DecimalValue);

Copy code to clipboardVB  C#

 

 

Step 11. Download the IronXL C# Library for FREEDownload DLL

 Download DLL

Manually install into your project

or

Install with NuGet

Install-Package IronXL.Excelnuget.org/packages/IronXL.Excel/

The first thing we need to do is install the IronXL.Excel library, adding Excel functionality to the .NET framework.

Installing IronXL.Excel, is most easily achieved using our NuGet package, although you may also choose to manually install the DLL to your project or to your global assembly cache.

Installing the IronXL Nuget Package
  1. In Visual Studio, right-click on the project select “Manage Nuget Packages …”
  2. Search for the IronXL.Excel package and install 

Another way to install is:

  1. Enter the Package Manager Console
  2. Type > Install-Package IronXL.Excel

PM > Install-Package IronXL.Excel

Additionally, you can view the package on the NuGet site here.

Direct Download Installation

Alternatively, we can start by downloading the IronXL .NET Excel DLL and manually installing into Visual Studio.

 

 

How To Tutorials2. Load a WorkBook

The WorkBook class represents an Excel sheet. To open an Excel File using C#, we use WorkBook.Load and specify the path of the Excel file (.xlsx).

  1. /**
  2. Load WorkBook
  3. anchor-load-a-workbook
  4. **/
  5. var workbook = WorkBook.Load(@”Spreadsheets\GDP.xlsx”);

Copy code to clipboardVB  C#

Sample: ExcelToDBProcessor

Each WorkBook can have multiple WorkSheet objects. These represent worksheets in the Excel document. If the sheet contains worksheets, retrieve them by name WorkBook.GetWorkSheet.

  1. var worksheet = workbook.GetWorkSheet(“GDPByCountry”);

Copy code to clipboardVB  C#

Sample: ExcelToDB

 

 

3. Create a WorkBook

To create a new WorkBook in memory, construct a new WorkBook with the sheet type.

  1. /**
  2. Create WorkBook
  3. anchor-create-a-workbook
  4. **/
  5. var workbook = new WorkBook(ExcelFileFormat.XLSX);

Copy code to clipboardVB  C#

Sample: ApiToExcelProcessor

Note: Use ExcelFileFormat.XLS for legacy for Microsoft Excel spreadsheets (95 and earlier).

 

 

4. Create a WorkSheet

Each “WorkBook” can have multiple WorkSheets. A “WorkSheet” is a sheet of data, while a WorkBook represents a collection of WorkSheets. This is how one workbook with two worksheets looks in Excel.

To create a new WorkSheet call WorkBook.CreateWorkSheet and pass the name of the worksheet.

  1. var worksheet = workbook.CreateWorkSheet(“Countries”);

Copy code to clipboardVB  C#

 

 

5. Get Cell Range

The “Range” class represents a two-dimensional collection of “Cell” objects. It represents a literal range of Excel cells. Obtain ranges by using the string indexer on a WorkSheet object.

The argument text is either the coordinate of a cell (e.g. “A1”) or a span of cells from left to right top to bottom (e.g. “B2:E5”). It is also possible to call GetRange on a WorkSheet.

  1. var range = worksheet[“D2:D101”];

Copy code to clipboardVB  C#

Sample: DataValidation

 

 

6. Edit Cell Values Within a Range

There are several ways to read or edit the values of cells within a Range. If the count is known, use a For loop.

  1. /**
  2. Edit Cell Values in Range
  3. anchor-edit-cell-values-within-a-range
  4. **/
  5. //Iterate through the rows
  6. for (var y = 2; y <= 101; y++)
  7. {
  8. var result = new PersonValidationResult { Row = y };
  9. results.Add(result);
  10. //Get all cells for the person
  11. var cells = worksheet[$”A{y}:E{y}”].ToList();
  12. //Validate the phone number (1 = B)
  13. var phoneNumber = cells[1].Value;
  14. result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);
  15. //Validate the email address (3 = D)
  16. result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);
  17. //Get the raw date in the format of Month Day[suffix], Year (4 = E)
  18. var rawDate = (string)cells[4].Value;
  19. result.DateErrorMessage = ValidateDate(rawDate);
  20. }

Copy code to clipboardVB  C#

Sample: DataValidation

 

 

7. Validate Spreadsheet Data

Use IronXL to validate a sheet of data. The DataValidation sample uses libphonenumber-csharp to validate phone numbers and uses standard C# APIs to validate email addresses and dates.

  1. /**
  2. Validate Spreadsheet Data
  3. anchor-validate-spreadsheet-data
  4. **/
  5. //Iterate through the rows
  6. for (var i = 2; i <= 101; i++)
  7. {
  8. var result = new PersonValidationResult { Row = i };
  9. results.Add(result);
  10. //Get all cells for the person
  11. var cells = worksheet[$”A{i}:E{i}”].ToList();
  12. //Validate the phone number (1 = B)
  13. var phoneNumber = cells[1].Value;
  14. result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);
  15. //Validate the email address (3 = D)
  16. result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);
  17. //Get the raw date in the format of Month Day[suffix], Year (4 = E)
  18. var rawDate = (string)cells[4].Value;
  19. result.DateErrorMessage = ValidateDate(rawDate);
  20. }

Copy code to clipboardVB  C#

The above code loops through each row in the spreadsheet and grabs the cells as a list. Each validates method checks the value of a cell and returns an error message if the value is invalid.

This code creates a new sheet, specifies headers, and outputs the error message results so that there is a log of invalid data.

  1. var resultsSheet = workbook.CreateWorkSheet(“Results”);
  2. resultsSheet[“A1”].Value = “Row”;
  3. resultsSheet[“B1”].Value = “Valid”;
  4. resultsSheet[“C1”].Value = “Phone Error”;
  5. resultsSheet[“D1”].Value = “Email Error”;
  6. resultsSheet[“E1”].Value = “Date Error”;
  7. for (var i = 0; i < results.Count; i++)
  8. {
  9. var result = results[i];
  10. resultsSheet[$”A{i + 2}”].Value = result.Row;
  11. resultsSheet[$”B{i + 2}”].Value = result.IsValid ? “Yes” : “No”;
  12. resultsSheet[$”C{i + 2}”].Value = result.PhoneNumberErrorMessage;
  13. resultsSheet[$”D{i + 2}”].Value = result.EmailErrorMessage;
  14. resultsSheet[$”E{i + 2}”].Value = result.DateErrorMessage;
  15. }
  16. workbook.SaveAs(@”Spreadsheets\PeopleValidated.xlsx”);

Copy code to clipboardVB  C#

 

 

8. Export Data using Entity Framework

Use IronXL to export data to a database or convert an Excel spreadsheet to a database. The ExcelToDB sample reads a spreadsheet with GDP by country and then exports that data to an SQLite.

It uses EntityFramework to build the database and then export the data line by line.

Add the SQLite Entity Framework NuGet packages.

 

 

EntityFramework allows you to create a model object that can export data to the database.

  1. public class Country
  2. {
  3. [Key]
  4. public Guid Key { get; set; }
  5. public string Name { get; set; }
  6. public decimal GDP { get; set; }
  7. }

Copy code to clipboardVB  C#

To use a different database, install the corresponding NuGet package and find the equivalent of UseSqLite()

  1. /**
  2. Export Data using Entity Framework
  3. anchor-export-data-using-entity-framework
  4. **/
  5. public class CountryContext : DbContext
  6. {
  7. public DbSet<Country> Countries { get; set; }
  8. public CountryContext()
  9. {
  10. //TODO: Make async
  11. Database.EnsureCreated();
  12. }
  13. /// <summary>
  14. /// Configure context to use Sqlite
  15. /// </summary>
  16. /// <param name=”optionsBuilder”></param>
  17. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
  18. {
  19. var connection = new SqliteConnection($”Data Source=Country.db”);
  20. connection.Open();
  21. var command = connection.CreateCommand();
  22. //Create the database if it doesn’t already exist
  23. command.CommandText = $”PRAGMA foreign_keys = ON;”;
  24. command.ExecuteNonQuery();
  25. optionsBuilder.UseSqlite(connection);
  26. base.OnConfiguring(optionsBuilder);
  27. }
  28. }

Copy code to clipboardVB  C#

Create a CountryContext, iterate through the range to create each record, and then SaveAsync to commit data to the database

  1. public async Task ProcessAsync()
  2. {
  3. //Get the first worksheet
  4. var workbook = WorkBook.Load(@”Spreadsheets\GDP.xlsx”);
  5. var worksheet = workbook.GetWorkSheet(“GDPByCountry”);
  6. //Create the database connection
  7. using (var countryContext = new CountryContext())
  8. {
  9. //Iterate through all the cells
  10. for (var i = 2; i <= 213; i++)
  11. {
  12. //Get the range from A-B
  13. var range = worksheet[$”A{i}:B{i}”].ToList();
  14. //Create a Country entity to be saved to the database
  15. var country = new Country
  16. {
  17. Name = (string)range[0].Value,
  18. GDP = (decimal)(double)range[1].Value
  19. };
  20. //Add the entity
  21. await countryContext.Countries.AddAsync(country);
  22. }
  23. //Commit changes to the database
  24. await countryContext.SaveChangesAsync();
  25. }
  26. }

Copy code to clipboardVB  C#

Sample: ExcelToDB

 

 

9. Add Formula to a Spreadsheet

Set formula of Cell‘s with the Formula property.

The code below iterates through each state and puts a percentage total in column C.

  1. /**
  2. Add Spreadsheet Formulae
  3. anchor-add-formulae-to-a-spreadsheet
  4. **/
  5. //Iterate through all rows with a value
  6. for (var y = 2; y < i; y++)
  7. {
  8. //Get the C cell
  9. var cell = sheet[$”C{y}”].First();
  10. //Set the formula for the Percentage of Total column
  11. cell.Formula = $”=B{y}/B{i}”;
  12. }

Copy code to clipboardVB  C#

Sample: AddFormulaeProcessor

 

 

10. Download Data from an API to Spreadsheet

The following call makes a REST call with RestClient.Net. It downloads JSON and converts it into a “List” of the type RestCountry. It is then easy to iterate through each country and save the data from the REST API to an Excel spreadsheet.

  1. /**
  2. Data API to Spreadsheet
  3. anchor-download-data-from-an-api-to-spreadsheet
  4. **/
  5. var client = new Client(new Uri(“https://restcountries.eu/rest/v2/”));
  6. List<RestCountry> countries = await client.GetAsync<List<RestCountry>>();

Copy code to clipboardVB  C#

Sample: ApiToExcel

This is what the API JSON data looks like.

 

 

The following code iterates through the countries and sets the Name, Population, Region, NumericCode, and Top 3 Languages in the spreadsheet.

  1. for (var i = 2; i < countries.Count; i++)
  2. {
  3. var country = countries[i];
  4. //Set the basic values
  5. worksheet[$”A{i}”].Value = country.name;
  6. worksheet[$”B{i}”].Value = country.population;
  7. worksheet[$”G{i}”].Value = country.region;
  8. worksheet[$”H{i}”].Value = country.numericCode;
  9. //Iterate through languages
  10. for (var x = 0; x < 3; x++)
  11. {
  12. if (x > (country.languages.Count – 1)) break;
  13. var language = country.languages[x];
  14. //Get the letter for the column
  15. var columnLetter = GetColumnLetter(4 + x);
  16. //Set the language name
  17. worksheet[$”{columnLetter}{i}”].Value = language.name;
  18. }
  19. }

Copy code to clipboardVB  C#

 

 

Object Reference and Resources

You may also find the IronXL class documentation within the Object Reference of great value.

In addition, there are other tutorials which may shed light in other aspects of IronXL.Excel including CreatingOpening, Writing Editing, Saving and Exporting XLS, XLSX and CSV files without using Excel Interop..

Summary

IronXL.Excel is alone .Net software library for reading a wide variety of spreadsheet formats. It does not require Microsoft Excel to be installed, and is not dependant on Interop.

 

11. Watch the Read Excel File C# Tutorial Video


Data & News supplied by www.cloudquote.io
Stock quotes supplied by Barchart
Quotes delayed at least 20 minutes.
By accessing this page, you agree to the following
Privacy Policy and Terms and Conditions.
 
 
Photos copyright by Jay Graham Photographer
Copyright © 2010-2020 Sausalito.com & California Media Partners, LLC. All rights reserved.