C# Read Excel File with Examples

This tutorial explains how to read an Excel file in C# and using libraries for everyday tasks similar validation, conversion to a database, saving information from Web APIs, and modifying formulae within the spreadsheet. This article references the IronXL code samples, which is a .Cyberspace 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 crave Excel to exist installed on your server or Interop. IronXL provides a faster and more intuitive API than Microsoft.Part.Interop.Excel.


Overview

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 precipitous lawmaking 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. Employ the WorkBook.Load method to read any XLS, XLSX or CSV document.
  3. Get Cell values using intuitive syntax: sheet["A11"].DecimalValue

IronXL Includes:

  • Defended product support from our .NET engineers
  • Easy installation via Microsoft Visual Studio
  • 30 mean solar day complimentary trial examination for development. Licenses from $499.

We will run into how easy information technology is to read Excel files in C# or VB.Internet 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.

            /** Read XLS or XLSX File ballast-read-an-xls-or-xlsx-file **/ using IronXL; using System.Linq;  //Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV WorkBook workbook = WorkBook.Load("examination.xlsx"); WorkSheet sail = workbook.WorkSheets.First(); //Select cells easily in Excel note and return the calculated value int cellValue = sheet["A2"].IntValue; // Read from Ranges of cells elegantly. foreach (var cell in sail["A2:A10"]) {     Panel.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text); }  ///Advanced Operations  //Calculate aggregate values such as Min, Max and Sum decimal sum = sheet["A2:A10"].Sum(); //Linq uniform decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);          
                /** Read XLS or XLSX File anchor-read-an-xls-or-xlsx-file **/ using IronXL; using System.Linq;  //Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV WorkBook workbook = WorkBook.Load("test.xlsx"); WorkSheet sheet = workbook.WorkSheets.First(); //Select cells easily in Excel note and render the calculated value int cellValue = sheet["A2"].IntValue; // Read from Ranges of cells elegantly. foreach (var cell in canvas["A2:A10"]) {     Panel.WriteLine("Cell {0} has value '{1}'", cell.AddressString, prison cell.Text); }  ///Advanced Operations  //Calculate aggregate values such as Min, Max and Sum decimal sum = canvas["A2:A10"].Sum(); //Linq compatible decimal max = canvas["A2:A10"].Max(c => c.DecimalValue);              
                ''' '''Read XLS or XLSX File '''anchor-read-an-xls-or-xlsx-file '''* Imports IronXL Imports Organisation.Linq  'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV Private workbook As WorkBook = WorkBook.Load("examination.xlsx") Individual sheet As WorkSheet = workbook.WorkSheets.Beginning() 'Select cells easily in Excel notation and render the calculated value Individual cellValue Every bit Integer = sheet("A2").IntValue ' Read from Ranges of cells elegantly. For Each cell In sail("A2:A10") 	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text) Side by side prison cell  '''Advanced Operations  'Summate aggregate values such as Min, Max and Sum Dim sum As Decimal = canvas("A2:A10").Sum() 'Linq uniform Dim max Every bit Decimal = canvass("A2:A10").Max(Function(c) c.DecimalValue)              

VB C#


Pace 1

ane. Download the IronXL C# Library for FREE

C# PDF DLL

Download DLL

or

C# Nuget Library for PDF

Install with NuGet

Install-Packet IronXL.Excel

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

Installing IronXL.Excel, is well-nigh easily accomplished using our NuGet package, although you may also cull to manually install the DLL to your project or to your global assembly enshroud.

Installing the IronXL Nuget Package

  1. In Visual Studio, correct-click on the projection select "Manage Nuget Packages ..."
  2. Search for the IronXL.Excel packet and install


Another mode to install is:

  1. Enter the Bundle Director Panel
  2. Type > Install-Parcel IronXL.Excel
                          PM > Install-Package IronXL.Excel          


Additionally, you tin can view the parcel on the NuGet site here.

Direct Download Installation

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


How To Tutorials

two. Load a WorkBook

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

            /** Load WorkBook ballast-load-a-workbook **/ var workbook = WorkBook.Load(@"Spreadsheets\\Gdp.xlsx");          
                /** Load WorkBook anchor-load-a-workbook **/ var workbook = WorkBook.Load(@"Spreadsheets\\Gross domestic product.xlsx");              
                ''' '''Load WorkBook '''anchor-load-a-workbook '''* Dim workbook = WorkBook.Load("Spreadsheets\\Gdp.xlsx")              

VB C#

Sample: ExcelToDBProcessor

Each WorkBook can take multiple WorkSheet objects. These correspond worksheets in the Excel document. If the sail contains worksheets, retrieve them by proper noun WorkBook.GetWorkSheet.

            var worksheet = workbook.GetWorkSheet("GDPByCountry");          
                var worksheet = workbook.GetWorkSheet("GDPByCountry");              
                Dim worksheet = workbook.GetWorkSheet("GDPByCountry")              

VB C#

Sample: ExcelToDB


3. Create a WorkBook

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

            /** Create WorkBook ballast-create-a-workbook **/ var workbook = new WorkBook(ExcelFileFormat.XLSX);          
                /** Create WorkBook anchor-create-a-workbook **/ var workbook = new WorkBook(ExcelFileFormat.XLSX);              
                ''' '''Create WorkBook '''ballast-create-a-workbook '''* Dim workbook Every bit New WorkBook(ExcelFileFormat.XLSX)              

VB C#

Sample: ApiToExcelProcessor

Notation: Use ExcelFileFormat.XLS for legacy for Microsoft Excel spreadsheets (95 and before).


four. Create a WorkSheet

Each "WorkBook" can take multiple WorkSheets. A "WorkSheet" is a sheet of information, while a WorkBook represents a collection of WorkSheets. This is how i workbook with 2 worksheets looks in Excel.

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

            var worksheet = workbook.CreateWorkSheet("Countries");          
                var worksheet = workbook.CreateWorkSheet("Countries");              
                Dim worksheet = workbook.CreateWorkSheet("Countries")              

VB C#


5. Get Cell Range

The "Range" form represents a two-dimensional drove of "Cell" objects. Information technology 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 jail cell (e.g. "A1") or a span of cells from left to right top to bottom (e.thousand. "B2:E5"). It is also possible to telephone call GetRange on a WorkSheet.

            var range = worksheet["D2:D101"];          
                var range = worksheet["D2:D101"];              
                Dim range = worksheet("D2:D101")              

VB 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.

            /** Edit Prison cell Values in Range ballast-edit-prison cell-values-within-a-range **/ //Iterate through the rows for (var y = ii; y <= 101; y++) {     var outcome = new PersonValidationResult { Row = y };     results.Add together(result);      //Get all cells for the person     var cells = worksheet[$"A{y}:E{y}"].ToList();      //Validate the phone number (i = B)     var phoneNumber = cells[1].Value;     result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (cord)phoneNumber);      //Validate the email address (3 = D)     event.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);      //Become the raw date in the format of Month Day[suffix], Year (4 = E)     var rawDate = (string)cells[iv].Value;     result.DateErrorMessage = ValidateDate(rawDate); }          
                /** Edit Prison cell Values in Range anchor-edit-jail cell-values-within-a-range **/ //Iterate through the rows for (var y = ii; y <= 101; y++) {     var event = new PersonValidationResult { Row = y };     results.Add(issue);      //Get all cells for the person     var cells = worksheet[$"A{y}:E{y}"].ToList();      //Validate the phone number (1 = B)     var phoneNumber = cells[1].Value;     result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (cord)phoneNumber);      //Validate the email accost (three = D)     result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);      //Get the raw date in the format of Month Day[suffix], Year (iv = E)     var rawDate = (string)cells[4].Value;     result.DateErrorMessage = ValidateDate(rawDate); }              
                ''' '''Edit Cell Values in Range '''anchor-edit-jail cell-values-within-a-range '''* 'Iterate through the rows For y = 2 To 101 	Dim result = New PersonValidationResult With {.Row = y} 	results.Add together(effect)  	'Get all cells for the person 	Dim cells = worksheet($"A{y}:E{y}").ToList()  	'Validate the telephone number (1 = B) 	Dim phoneNumber = cells(i).Value 	result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))  	'Validate the e-mail address (3 = D) 	event.EmailErrorMessage = ValidateEmailAddress(CStr(cells(3).Value))  	'Get the raw engagement in the format of Calendar month Day[suffix], Yr (4 = E) 	Dim rawDate = CStr(cells(iv).Value) 	outcome.DateErrorMessage = ValidateDate(rawDate) Next y              

VB C#

Sample: DataValidation


seven. Validate Spreadsheet Data

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

            /** Validate Spreadsheet Data anchor-validate-spreadsheet-data **/ //Iterate through the rows for (var i = 2; i <= 101; i++) {     var issue = new PersonValidationResult { Row = i };     results.Add(result);      //Get all cells for the person     var cells = worksheet[$"A{i}:E{i}"].ToList();      //Validate the telephone number (1 = B)     var phoneNumber = cells[1].Value;     result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);      //Validate the email address (3 = D)     result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);      //Get the raw date in the format of Month Mean solar day[suffix], Year (4 = E)     var rawDate = (cord)cells[iv].Value;     result.DateErrorMessage = ValidateDate(rawDate); }          
                /** Validate Spreadsheet Information anchor-validate-spreadsheet-data **/ //Iterate through the rows for (var i = 2; i <= 101; i++) {     var result = new PersonValidationResult { Row = i };     results.Add(upshot);      //Become all cells for the person     var cells = worksheet[$"A{i}:E{i}"].ToList();      //Validate the phone number (1 = B)     var phoneNumber = cells[1].Value;     effect.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (cord)phoneNumber);      //Validate the e-mail address (3 = D)     result.EmailErrorMessage = ValidateEmailAddress((cord)cells[3].Value);      //Get the raw date in the format of Calendar month Day[suffix], Twelvemonth (4 = E)     var rawDate = (cord)cells[4].Value;     result.DateErrorMessage = ValidateDate(rawDate); }              
                ''' '''Validate Spreadsheet Data '''anchor-validate-spreadsheet-data '''* 'Iterate through the rows For i = two To 101 	Dim result = New PersonValidationResult With {.Row = i} 	results.Add(result)  	'Get all cells for the person 	Dim cells = worksheet($"A{i}:E{i}").ToList()  	'Validate the phone number (1 = B) 	Dim phoneNumber = cells(i).Value 	result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))  	'Validate the email address (iii = D) 	result.EmailErrorMessage = ValidateEmailAddress(CStr(cells(3).Value))  	'Get the raw date in the format of Month Mean solar day[suffix], Year (4 = East) 	Dim rawDate = CStr(cells(4).Value) 	result.DateErrorMessage = ValidateDate(rawDate) Next i              

VB C#

The in a higher place code loops through each row in the spreadsheet and grabs the cells as a list. Each validates method checks the value of a jail 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.

            var resultsSheet = workbook.CreateWorkSheet("Results");  resultsSheet["A1"].Value = "Row"; resultsSheet["B1"].Value = "Valid"; resultsSheet["C1"].Value = "Phone Fault"; resultsSheet["D1"].Value = "Electronic mail Error"; resultsSheet["E1"].Value = "Date Error";  for (var i = 0; i < results.Count; i++) {     var result = results[i];     resultsSheet[$"A{i + two}"].Value = consequence.Row;     resultsSheet[$"B{i + ii}"].Value = outcome.IsValid ? "Yes" : "No";     resultsSheet[$"C{i + two}"].Value = upshot.PhoneNumberErrorMessage;     resultsSheet[$"D{i + two}"].Value = result.EmailErrorMessage;     resultsSheet[$"East{i + two}"].Value = result.DateErrorMessage; }  workbook.SaveAs(@"Spreadsheets\\PeopleValidated.xlsx");          
                var resultsSheet = workbook.CreateWorkSheet("Results");  resultsSheet["A1"].Value = "Row"; resultsSheet["B1"].Value = "Valid"; resultsSheet["C1"].Value = "Phone Fault"; resultsSheet["D1"].Value = "Email Error"; resultsSheet["E1"].Value = "Appointment Error";  for (var i = 0; i < results.Count; i++) {     var event = results[i];     resultsSheet[$"A{i + 2}"].Value = result.Row;     resultsSheet[$"B{i + 2}"].Value = result.IsValid ? "Yes" : "No";     resultsSheet[$"C{i + two}"].Value = consequence.PhoneNumberErrorMessage;     resultsSheet[$"D{i + ii}"].Value = consequence.EmailErrorMessage;     resultsSheet[$"E{i + ii}"].Value = result.DateErrorMessage; }  workbook.SaveAs(@"Spreadsheets\\PeopleValidated.xlsx");              
                Dim resultsSheet = workbook.CreateWorkSheet("Results")  resultsSheet("A1").Value = "Row" resultsSheet("B1").Value = "Valid" resultsSheet("C1").Value = "Phone Error" resultsSheet("D1").Value = "Email Mistake" resultsSheet("E1").Value = "Date Fault"  For i = 0 To results.Count - 1 	Dim result = results(i) 	resultsSheet($"A{i + 2}").Value = event.Row 	resultsSheet($"B{i + 2}").Value = If(result.IsValid, "Yes", "No") 	resultsSheet($"C{i + 2}").Value = event.PhoneNumberErrorMessage 	resultsSheet($"D{i + ii}").Value = upshot.EmailErrorMessage 	resultsSheet($"E{i + ii}").Value = result.DateErrorMessage Next i  workbook.SaveAs("Spreadsheets\\PeopleValidated.xlsx")              

VB C#


8. Export Data using Entity Framework

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

It uses EntityFramework to build the database and so export the information line past line.

Add the SQLite Entity Framework NuGet packages.

EntityFramework allows y'all to create a model object that can export data to the database.

            public course Country {     [Primal]     public Guid Central { get; set; }     public string Name { get; set; }     public decimal Gross domestic product { get; set; } }          
                public class Land {     [Key]     public Guid Fundamental { go; set; }     public string Proper noun { get; set; }     public decimal Gdp { get; prepare; } }              
                Public Class Country 	<Key> 	Public Holding Key() As Guid 	Public Property Name() Equally String 	Public Property GDP() As Decimal End Form              

VB C#

To utilise a different database, install the respective NuGet parcel and discover the equivalent of UseSqLite()

            /** Export Data using Entity Framework ballast-consign-data-using-entity-framework **/ public grade CountryContext : DbContext {     public DbSet<Country> Countries { get; set; }      public CountryContext()     {         //TODO: Make async         Database.EnsureCreated();     }      /// <summary>     /// Configure context to use Sqlite     /// </summary>     /// <param name="optionsBuilder"></param>     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)     {         var connection = new SqliteConnection($"Information Source=Country.db");         connectedness.Open();          var control = connection.CreateCommand();          //Create the database if it doesn't already exist         command.CommandText = $"PRAGMA foreign_keys = ON;";         command.ExecuteNonQuery();          optionsBuilder.UseSqlite(connection);          base of operations.OnConfiguring(optionsBuilder);     }  }          
                /** Export Data using Entity Framework anchor-export-data-using-entity-framework **/ public class CountryContext : DbContext {     public DbSet<State> Countries { become; set; }      public CountryContext()     {         //TODO: Make async         Database.EnsureCreated();     }      /// <summary>     /// Configure context to use Sqlite     /// </summary>     /// <param name="optionsBuilder"></param>     protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)     {         var connection = new SqliteConnection($"Data Source=Land.db");         connection.Open();          var command = connection.CreateCommand();          //Create the database if it doesn't already exist         command.CommandText = $"PRAGMA foreign_keys = ON;";         command.ExecuteNonQuery();          optionsBuilder.UseSqlite(connection);          base.OnConfiguring(optionsBuilder);     }  }              
                ''' '''Export Information using Entity Framework '''anchor-export-data-using-entity-framework '''* Public Course CountryContext 	Inherits DbContext  	Public Property Countries() As DbSet(Of Country)  	Public Sub New() 		'TODO: Make async 		Database.EnsureCreated() 	End Sub  	''' <summary> 	''' Configure context to utilise Sqlite 	''' </summary> 	''' <param name="optionsBuilder"></param> 	Protected Overrides Sub OnConfiguring(ByVal optionsBuilder As DbContextOptionsBuilder) 		Dim connexion = New SqliteConnection($"Data Source=State.db") 		connexion.Open()  		Dim command = connection.CreateCommand()  		'Create the database if it doesn't already exist 		command.CommandText = $"PRAGMA foreign_keys = ON;" 		command.ExecuteNonQuery()  		optionsBuilder.UseSqlite(connectedness)  		MyBase.OnConfiguring(optionsBuilder) 	End Sub  Terminate Class              

VB C#

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

            public async Chore ProcessAsync() {     //Become the beginning worksheet     var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");     var worksheet = workbook.GetWorkSheet("GDPByCountry");      //Create the database connection     using (var countryContext = new CountryContext())     {         //Iterate through all the cells         for (var i = 2; i <= 213; i++)         {             //Go the range from A-B             var range = worksheet[$"A{i}:B{i}"].ToList();              //Create a Land entity to exist saved to the database             var country = new Country             {                 Name = (string)range[0].Value,                 Gdp = (decimal)(double)range[1].Value             };              //Add the entity              await countryContext.Countries.AddAsync(land);         }          //Commit changes to the database         await countryContext.SaveChangesAsync();     } }          
                public async Chore ProcessAsync() {     //Get the kickoff worksheet     var workbook = WorkBook.Load(@"Spreadsheets\\GDP.xlsx");     var worksheet = workbook.GetWorkSheet("GDPByCountry");      //Create the database connectedness     using (var countryContext = new CountryContext())     {         //Iterate through all the cells         for (var i = ii; i <= 213; i++)         {             //Get the range from A-B             var range = worksheet[$"A{i}:B{i}"].ToList();              //Create a Country entity to exist saved to the database             var land = new Land             {                 Name = (string)range[0].Value,                 GDP = (decimal)(double)range[1].Value             };              //Add the entity              await countryContext.Countries.AddAsync(country);         }          //Commit changes to the database         await countryContext.SaveChangesAsync();     } }              
                Public Async Function ProcessAsync() As Job 	'Become the first worksheet 	Dim workbook = WorkBook.Load("Spreadsheets\\Gdp.xlsx") 	Dim worksheet = workbook.GetWorkSheet("GDPByCountry")  	'Create the database connectedness 	Using countryContext As New CountryContext() 		'Iterate through all the cells 		For i = 2 To 213 			'Get the range from A-B 			Dim range = worksheet($"A{i}:B{i}").ToList()  			'Create a Country entity to be saved to the database 			Dim country Every bit New Country With { 				.Proper name = CStr(range(0).Value), 				.Gross domestic product = CDec(CDbl(range(ane).Value)) 			}  			'Add the entity  			Await countryContext.Countries.AddAsync(country) 		Next i  		'Commit changes to the database 		Look countryContext.SaveChangesAsync() 	Stop Using End Function              

VB C#

Sample: ExcelToDB


ix. Add Formula to a Spreadsheet

Ready formula of Jail cell's with the Formula holding.

The lawmaking below iterates through each land and puts a percentage total in column C.

            /** Add Spreadsheet Formulae ballast-add together-formulae-to-a-spreadsheet **/ //Iterate through all rows with a value for (var y = 2; y < i; y++) {     //Get the C cell     var cell = sheet[$"C{y}"].Offset();      //Set the formula for the Percentage of Total column     cell.Formula = $"=B{y}/B{i}"; }          
                /** Add together Spreadsheet Formulae anchor-add-formulae-to-a-spreadsheet **/ //Iterate through all rows with a value for (var y = 2; y < i; y++) {     //Get the C prison cell     var cell = canvass[$"C{y}"].First();      //Set the formula for the Percentage of Total column     cell.Formula = $"=B{y}/B{i}"; }              
                ''' '''Add Spreadsheet Formulae '''anchor-add-formulae-to-a-spreadsheet '''* 'Iterate through all rows with a value Dim y = two Do While y < i 	'Get the C cell 	Dim jail cell = canvass($"C{y}").Showtime()  	'Set the formula for the Percentage of Total column 	prison cell.Formula = $"=B{y}/B{i}" 	y += ane Loop              

VB C#

Sample: AddFormulaeProcessor


10. Download Data from an API to Spreadsheet

The following phone call makes a Rest telephone call with RestClient.Cyberspace. Information technology downloads JSON and converts information technology into a "List" of the blazon RestCountry. Information technology is and then easy to iterate through each country and save the data from the REST API to an Excel spreadsheet.

            /** Data API to Spreadsheet ballast-download-data-from-an-api-to-spreadsheet **/ var client = new Client(new Uri("https://restcountries.eu/rest/v2/")); List<RestCountry> countries = look client.GetAsync<Listing<RestCountry>>();          
                /** Data API to Spreadsheet anchor-download-data-from-an-api-to-spreadsheet **/ var client = new Client(new Uri("https://restcountries.eu/rest/v2/")); List<RestCountry> countries = look client.GetAsync<List<RestCountry>>();              
                ''' '''Information API to Spreadsheet '''ballast-download-data-from-an-api-to-spreadsheet '''* Dim customer As New Client(New Uri("https://restcountries.eu/residue/v2/")) Dim countries As List(Of RestCountry) = Await client.GetAsync(Of List(Of RestCountry))()              

VB C#

Sample: ApiToExcel

This is what the API JSON data looks similar.

The post-obit code iterates through the countries and sets the Proper name, Population, Region, NumericCode, and Top iii Languages in the spreadsheet.

            for (var i = ii; i < countries.Count; i++) {     var state = countries[i];      //Set the basic values     worksheet[$"A{i}"].Value = state.name;     worksheet[$"B{i}"].Value = state.population;     worksheet[$"G{i}"].Value = country.region;     worksheet[$"H{i}"].Value = country.numericCode;      //Iterate through languages     for (var x = 0; x < iii; 10++)     {         if (x > (country.languages.Count - 1)) interruption;          var language = country.languages[x];          //Get the alphabetic character for the column         var columnLetter = GetColumnLetter(4 + x);          //Set the linguistic communication name         worksheet[$"{columnLetter}{i}"].Value = language.name;     } }          
                for (var i = two; i < countries.Count; i++) {     var land = countries[i];      //Set the bones values     worksheet[$"A{i}"].Value = state.name;     worksheet[$"B{i}"].Value = country.population;     worksheet[$"One thousand{i}"].Value = country.region;     worksheet[$"H{i}"].Value = country.numericCode;      //Iterate through languages     for (var 10 = 0; ten < 3; ten++)     {         if (x > (country.languages.Count - 1)) break;          var linguistic communication = country.languages[x];          //Go the letter for the column         var columnLetter = GetColumnLetter(four + x);          //Set the language name         worksheet[$"{columnLetter}{i}"].Value = linguistic communication.proper name;     } }              
                For i = 2 To countries.Count - one 	Dim land = countries(i)  	'Set the basic values 	worksheet($"A{i}").Value = state.name 	worksheet($"B{i}").Value = land.population 	worksheet($"Grand{i}").Value = country.region 	worksheet($"H{i}").Value = state.numericCode  	'Iterate through languages 	For 10 = 0 To ii 		If ten > (country.languages.Count - 1) So 			Exit For 		Stop If  		Dim language = country.languages(x)  		'Become the letter for the cavalcade 		Dim columnLetter = GetColumnLetter(4 + x)  		'Set the language name 		worksheet($"{columnLetter}{i}").Value = language.name 	Side by side 10 Next i              

VB C#


Object Reference and Resource

You may too find the IronXL class documentation within the Object Reference of neat value.

In addition, there are other tutorials which may shed light in other aspects of IronXL.Excel including Creating, Opening, 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 diversity of spreadsheet formats. It does non crave Microsoft Excel to be installed, and is not dependant on Interop.


11. Watch the Read Excel File C# Tutorial Video


Tutorial Quick Access

Download this Tutorial as C# Source Lawmaking

The full gratuitous C# for Excel Source Code for this tutorial is available to download as a zipped Visual Studio 2017 project file.

Download

Explore this Tutorial on GitHub

The source code for this project is available in C# and VB.NET on GitHub.

Apply this code as an like shooting fish in a barrel way to go upwards and running in simply a few minutes. The project is saved every bit a Microsoft Visual Studio 2017 project, just is compatible with any .NET IDE.

How to Read Excel File in C# on GitHub

View the API Reference

Explore the API Reference for IronXL, outlining the details of all of IronXL'south features, namespaces, classes, methods fields and enums.

View the API Reference

.Net Solution Director working with Microsoft Excel document IO

Christian Findlay

Software Evolution Team Atomic number 82

Christian builds software for the health industry and leads upward a squad. Christian has years of experience integrating with systems of all kinds. IronXL allows Christian to import and dispense data from different sources to automate repetitive tasks and validate input information from 3rd party sources.