C# Read Excel File with Examples

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 Spider web APIs, and modifying formulas inside 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 exist installed on your server or Interop. IronXL provides a faster and more intuitive API than Microsoft.Role.Interop.Excel.


Overview

Read Data from Excel file using IronXL

IronXL is a .Cyberspace 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 bundle or by downloading the .Net Excel DLL.
  2. Use the WorkBook.Load method to read any XLS, XLSX or CSV document.
  3. Go Cell values using intuitive syntax: canvas["A11"].DecimalValue

IronXL Includes:

  • Dedicated product support from our .Cyberspace engineers
  • Easy installation via Microsoft Visual Studio
  • 30 twenty-four hours free trial exam for development. Licenses from $749.

We will come across 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 nosotros tin see how to read the excel file efficiently without Interop in C#. The concluding Avant-garde Operations prove 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("test.xlsx"); WorkSheet sheet = workbook.WorkSheets.Kickoff(); //Select cells easily in Excel notation and return the calculated value int cellValue = sheet["A2"].IntValue; // Read from Ranges of cells elegantly. foreach (var jail cell in sheet["A2:A10"]) {     Panel.WriteLine("Jail cell {0} has value '{1}'", cell.AddressString, cell.Text); }  ///Avant-garde Operations  //Calculate aggregate values such equally Min, Max and Sum decimal sum = canvass["A2:A10"].Sum(); //Linq uniform decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);          
                /** Read XLS or XLSX File ballast-read-an-xls-or-xlsx-file **/ using IronXL; using Arrangement.Linq;  //Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV WorkBook workbook = WorkBook.Load("test.xlsx"); WorkSheet canvass = workbook.WorkSheets.Outset(); //Select cells hands in Excel note and return the calculated value int cellValue = sheet["A2"].IntValue; // Read from Ranges of cells elegantly. foreach (var cell in sheet["A2:A10"]) {     Console.WriteLine("Jail cell {0} has value '{1}'", cell.AddressString, cell.Text); }  ///Advanced Operations  //Calculate aggregate values such as Min, Max and Sum decimal sum = canvas["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 '''* Imports IronXL Imports System.Linq  'Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV Private workbook As WorkBook = WorkBook.Load("exam.xlsx") Private sheet As WorkSheet = workbook.WorkSheets.First() 'Select cells hands in Excel notation and return the calculated value Private cellValue As Integer = sheet("A2").IntValue ' Read from Ranges of cells elegantly. For Each jail cell In sheet("A2:A10") 	Panel.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text) Next cell  '''Advanced Operations  'Summate aggregate values such as Min, Max and Sum Dim sum Every bit Decimal = canvas("A2:A10").Sum() 'Linq compatible Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)              

VB C#


Pace 1

i. Download the IronXL C# Library for Free

C# PDF DLL

Download DLL

or

C# NuGet Library for PDF

Install with NuGet

Install-Package IronXL.Excel

The get-go affair 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 yous may too 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 Managing director Console
  2. Type > Install-Bundle IronXL.Excel
                          PM > Install-Packet IronXL.Excel          


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

Direct Download Installation

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


How To Tutorials

2. Load a WorkBook

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

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

VB C#

Sample: ExcelToDBProcessor

Each WorkBook tin can have multiple WorkSheet objects. These represent worksheets in the Excel document. If the sheet contains worksheets, retrieve them by name 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 anchor-create-a-workbook **/ var workbook = new WorkBook(ExcelFileFormat.XLSX);          
                /** Create WorkBook anchor-create-a-workbook **/ var workbook = new WorkBook(ExcelFileFormat.XLSX);              
                ''' '''Create WorkBook '''anchor-create-a-workbook '''* Dim workbook As New WorkBook(ExcelFileFormat.XLSX)              

VB C#

Sample: ApiToExcelProcessor

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


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.

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

VB C#


5. Get Cell Range

The "Range" course represents a two-dimensional collection of "Prison cell" objects. It represents a literal range of Excel cells. Obtain ranges past using the cord 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 lesser (e.g. "B2:E5"). It is also possible to call GetRange on a WorkSheet.

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

VB C#

Sample: DataValidation


half dozen. Edit Cell Values Within a Range

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

            /** Edit Cell Values in Range ballast-edit-cell-values-within-a-range **/ //Iterate through the rows for (var y = 2; y <= 101; y++) {     var issue = new PersonValidationResult { Row = y };     results.Add(issue);      //Get all cells for the person     var cells = worksheet[$"A{y}:E{y}"].ToList();      //Validate the telephone number (i = B)     var phoneNumber = cells[1].Value;     effect.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);      //Validate the email accost (three = D)     issue.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);      //Get the raw date in the format of Month Day[suffix], Twelvemonth (iv = East)     var rawDate = (string)cells[4].Value;     result.DateErrorMessage = ValidateDate(rawDate); }          
                /** Edit Cell Values in Range ballast-edit-cell-values-inside-a-range **/ //Iterate through the rows for (var y = 2; y <= 101; y++) {     var result = new PersonValidationResult { Row = y };     results.Add together(event);      //Get all cells for the person     var cells = worksheet[$"A{y}:Eastward{y}"].ToList();      //Validate the phone number (i = B)     var phoneNumber = cells[ane].Value;     result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (cord)phoneNumber);      //Validate the email address (3 = D)     upshot.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);      //Get the raw date in the format of Month Day[suffix], Twelvemonth (4 = East)     var rawDate = (cord)cells[four].Value;     upshot.DateErrorMessage = ValidateDate(rawDate); }              
                ''' '''Edit Jail 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(event)  	'Get all cells for the person 	Dim cells = worksheet($"A{y}:Due east{y}").ToList()  	'Validate the phone number (one = B) 	Dim phoneNumber = cells(1).Value 	event.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))  	'Validate the email accost (3 = D) 	result.EmailErrorMessage = ValidateEmailAddress(CStr(cells(3).Value))  	'Get the raw date in the format of Month 24-hour interval[suffix], Year (4 = Eastward) 	Dim rawDate = CStr(cells(4).Value) 	effect.DateErrorMessage = ValidateDate(rawDate) Next y              

VB C#

Sample: DataValidation


seven. 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 e-mail addresses and dates.

            /** Validate Spreadsheet Data anchor-validate-spreadsheet-data **/ //Iterate through the rows for (var i = 2; i <= 101; i++) {     var consequence = new PersonValidationResult { Row = i };     results.Add(consequence);      //Get all cells for the person     var cells = worksheet[$"A{i}:E{i}"].ToList();      //Validate the phone number (one = B)     var phoneNumber = cells[i].Value;     result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber);      //Validate the electronic mail address (3 = D)     result.EmailErrorMessage = ValidateEmailAddress((cord)cells[3].Value);      //Become the raw date in the format of Month Mean solar day[suffix], Year (4 = E)     var rawDate = (cord)cells[four].Value;     issue.DateErrorMessage = ValidateDate(rawDate); }          
                /** Validate Spreadsheet Data anchor-validate-spreadsheet-data **/ //Iterate through the rows for (var i = ii; i <= 101; i++) {     var result = new PersonValidationResult { Row = i };     results.Add(result);      //Get all cells for the person     var cells = worksheet[$"A{i}:E{i}"].ToList();      //Validate the phone number (1 = B)     var phoneNumber = cells[1].Value;     event.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (cord)phoneNumber);      //Validate the e-mail accost (3 = D)     effect.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);      //Get the raw engagement in the format of Month Mean solar day[suffix], Year (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 = 2 To 101 	Dim event = New PersonValidationResult With {.Row = i} 	results.Add(effect)  	'Get all cells for the person 	Dim cells = worksheet($"A{i}:E{i}").ToList()  	'Validate the phone number (one = B) 	Dim phoneNumber = cells(i).Value 	result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))  	'Validate the e-mail address (3 = D) 	effect.EmailErrorMessage = ValidateEmailAddress(CStr(cells(3).Value))  	'Become the raw date in the format of Month Day[suffix], Yr (4 = Eastward) 	Dim rawDate = CStr(cells(4).Value) 	result.DateErrorMessage = ValidateDate(rawDate) Next i              

VB 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 jail cell and returns an error bulletin if the value is invalid.

This code creates a new canvas, 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 Error"; resultsSheet["D1"].Value = "Email Fault"; resultsSheet["E1"].Value = "Date Fault";  for (var i = 0; i < results.Count; i++) {     var result = results[i];     resultsSheet[$"A{i + 2}"].Value = consequence.Row;     resultsSheet[$"B{i + 2}"].Value = result.IsValid ? "Yeah" : "No";     resultsSheet[$"C{i + 2}"].Value = effect.PhoneNumberErrorMessage;     resultsSheet[$"D{i + 2}"].Value = upshot.EmailErrorMessage;     resultsSheet[$"E{i + 2}"].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 Mistake"; resultsSheet["D1"].Value = "Email Error"; resultsSheet["E1"].Value = "Engagement Error";  for (var i = 0; i < results.Count; i++) {     var consequence = results[i];     resultsSheet[$"A{i + 2}"].Value = result.Row;     resultsSheet[$"B{i + 2}"].Value = consequence.IsValid ? "Yep" : "No";     resultsSheet[$"C{i + two}"].Value = issue.PhoneNumberErrorMessage;     resultsSheet[$"D{i + 2}"].Value = result.EmailErrorMessage;     resultsSheet[$"E{i + two}"].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 = "E-mail Fault" resultsSheet("E1").Value = "Date Error"  For i = 0 To results.Count - 1 	Dim result = results(i) 	resultsSheet($"A{i + ii}").Value = result.Row 	resultsSheet($"B{i + 2}").Value = If(result.IsValid, "Yes", "No") 	resultsSheet($"C{i + 2}").Value = effect.PhoneNumberErrorMessage 	resultsSheet($"D{i + 2}").Value = outcome.EmailErrorMessage 	resultsSheet($"E{i + 2}").Value = effect.DateErrorMessage Next i  workbook.SaveAs("Spreadsheets\\PeopleValidated.xlsx")              

VB C#


8. Consign 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 tin export data to the database.

            public class Country {     [Primal]     public Guid Key { get; prepare; }     public cord Name { get; set; }     public decimal Gdp { become; prepare; } }          
                public class State {     [Central]     public Guid Key { become; ready; }     public string Name { get; gear up; }     public decimal Gross domestic product { get; set; } }              
                Public Grade Country 	<Central> 	Public Property Fundamental() As Guid 	Public Holding Proper name() Every bit String 	Public Property Gdp() As Decimal End Class              

VB C#

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

            /** Consign Information using Entity Framework anchor-export-information-using-entity-framework **/ public class CountryContext : DbContext {     public DbSet<Country> Countries { get; fix; }      public CountryContext()     {         //TODO: Make async         Database.EnsureCreated();     }      /// <summary>     /// Configure context to employ 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 be         command.CommandText = $"PRAGMA foreign_keys = ON;";         command.ExecuteNonQuery();          optionsBuilder.UseSqlite(connection);          base of operations.OnConfiguring(optionsBuilder);     }  }          
                /** Export Data using Entity Framework ballast-export-data-using-entity-framework **/ public grade CountryContext : DbContext {     public DbSet<Country> 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=State.db");         connection.Open();          var control = connection.CreateCommand();          //Create the database if it doesn't already exist         command.CommandText = $"PRAGMA foreign_keys = ON;";         command.ExecuteNonQuery();          optionsBuilder.UseSqlite(connectedness);          base.OnConfiguring(optionsBuilder);     }  }              
                ''' '''Export Data using Entity Framework '''anchor-export-data-using-entity-framework '''* Public Form CountryContext 	Inherits DbContext  	Public Belongings Countries() As DbSet(Of Country)  	Public Sub New() 		'TODO: Make async 		Database.EnsureCreated() 	Finish Sub  	''' <summary> 	''' Configure context to use Sqlite 	''' </summary> 	''' <param name="optionsBuilder"></param> 	Protected Overrides Sub OnConfiguring(ByVal optionsBuilder As DbContextOptionsBuilder) 		Dim connection = New SqliteConnection($"Data Source=State.db") 		connection.Open()  		Dim control = 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  Cease Grade              

VB C#

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

            public async Job ProcessAsync() {     //Get the kickoff worksheet     var workbook = WorkBook.Load(@"Spreadsheets\\Gross domestic product.xlsx");     var worksheet = workbook.GetWorkSheet("GDPByCountry");      //Create the database connection     using (var countryContext = new CountryContext())     {         //Iterate through all the cells         for (var i = two; i <= 213; i++)         {             //Get the range from A-B             var range = worksheet[$"A{i}:B{i}"].ToList();              //Create a Land entity to be saved to the database             var country = new Land             {                 Name = (string)range[0].Value,                 Gross domestic product = (decimal)(double)range[1].Value             };              //Add the entity              look countryContext.Countries.AddAsync(state);         }          //Commit changes to the database         await countryContext.SaveChangesAsync();     } }          
                public async Task ProcessAsync() {     //Get the commencement 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++)         {             //Get the range from A-B             var range = worksheet[$"A{i}:B{i}"].ToList();              //Create a Country entity to be saved to the database             var state = new State             {                 Name = (string)range[0].Value,                 Gross domestic product = (decimal)(double)range[ane].Value             };              //Add the entity              await countryContext.Countries.AddAsync(land);         }          //Commit changes to the database         expect countryContext.SaveChangesAsync();     } }              
                Public Async Role ProcessAsync() Equally Job 	'Get the outset worksheet 	Dim workbook = WorkBook.Load("Spreadsheets\\GDP.xlsx") 	Dim worksheet = workbook.GetWorkSheet("GDPByCountry")  	'Create the database connection 	Using countryContext Equally 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 As New Country With { 				.Name = CStr(range(0).Value), 				.Gdp = CDec(CDbl(range(ane).Value)) 			}  			'Add the entity  			Await countryContext.Countries.AddAsync(land) 		Side by side i  		'Commit changes to the database 		Await countryContext.SaveChangesAsync() 	Terminate Using End Role              

VB C#

Sample: ExcelToDB


nine. Add together Formula to a Spreadsheet

Gear up formula of Cell's with the Formula property.

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

            /** Add together Spreadsheet Formulae ballast-add-formulae-to-a-spreadsheet **/ //Iterate through all rows with a value for (var y = 2; y < i; y++) {     //Go the C jail cell     var cell = sheet[$"C{y}"].Start();      //Prepare the formula for the Percentage of Total column     prison 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++) {     //Become the C cell     var jail cell = sheet[$"C{y}"].First();      //Set the formula for the Pct of Total column     cell.Formula = $"=B{y}/B{i}"; }              
                ''' '''Add Spreadsheet Formulae '''ballast-add together-formulae-to-a-spreadsheet '''* 'Iterate through all rows with a value Dim y = 2 Do While y < i 	'Go the C cell 	Dim cell = sheet($"C{y}").First()  	'Prepare the formula for the Percentage of Full cavalcade 	cell.Formula = $"=B{y}/B{i}" 	y += 1 Loop              

VB C#

Sample: AddFormulaeProcessor


x. Download Data from an API to Spreadsheet

The following call makes a REST telephone call with RestClient.Cyberspace. Information technology downloads JSON and converts it into a "Listing" of the type RestCountry. It is and so easy to iterate through each country and relieve the information from the Rest API to an Excel spreadsheet.

            /** Data API to Spreadsheet ballast-download-information-from-an-api-to-spreadsheet **/ var client = new Client(new Uri("https://restcountries.eu/residuum/v2/")); List<RestCountry> countries = expect client.GetAsync<Listing<RestCountry>>();          
                /** Information API to Spreadsheet ballast-download-data-from-an-api-to-spreadsheet **/ var client = new Client(new Uri("https://restcountries.eu/residual/v2/")); List<RestCountry> countries = await customer.GetAsync<List<RestCountry>>();              
                ''' '''Data API to Spreadsheet '''anchor-download-data-from-an-api-to-spreadsheet '''* Dim customer As New Client(New Uri("https://restcountries.eu/residual/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 like.

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

            for (var i = 2; i < countries.Count; i++) {     var land = countries[i];      //Set up the basic values     worksheet[$"A{i}"].Value = land.name;     worksheet[$"B{i}"].Value = country.population;     worksheet[$"G{i}"].Value = country.region;     worksheet[$"H{i}"].Value = country.numericCode;      //Iterate through languages     for (var 10 = 0; x < iii; x++)     {         if (x > (country.languages.Count - one)) break;          var linguistic communication = country.languages[ten];          //Get the letter for the column         var columnLetter = GetColumnLetter(4 + x);          //Set the linguistic communication name         worksheet[$"{columnLetter}{i}"].Value = language.proper name;     } }          
                for (var i = 2; i < countries.Count; i++) {     var country = countries[i];      //Fix the basic values     worksheet[$"A{i}"].Value = country.name;     worksheet[$"B{i}"].Value = state.population;     worksheet[$"One thousand{i}"].Value = country.region;     worksheet[$"H{i}"].Value = land.numericCode;      //Iterate through languages     for (var 10 = 0; x < three; x++)     {         if (x > (state.languages.Count - 1)) break;          var language = country.languages[10];          //Get the letter for the column         var columnLetter = GetColumnLetter(4 + 10);          //Prepare the language name         worksheet[$"{columnLetter}{i}"].Value = language.proper noun;     } }              
                For i = 2 To countries.Count - 1 	Dim state = countries(i)  	'Gear up the basic values 	worksheet($"A{i}").Value = country.proper noun 	worksheet($"B{i}").Value = country.population 	worksheet($"G{i}").Value = country.region 	worksheet($"H{i}").Value = country.numericCode  	'Iterate through languages 	For x = 0 To 2 		If x > (state.languages.Count - i) Then 			Exit For 		Terminate If  		Dim language = state.languages(x)  		'Become the letter for the column 		Dim columnLetter = GetColumnLetter(4 + 10)  		'Set the language name 		worksheet($"{columnLetter}{i}").Value = language.name 	Next x Next i              

VB C#


Object Reference and Resources

Y'all may also find the IronXL grade documentation within the Object Reference of great value.

In addition, in that location 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 solitary .NET software library for reading a wide multifariousness of spreadsheet formats. It does not require Microsoft Excel to be installed, and is not dependant on Interop.


Tutorial Quick Access

Download this Tutorial every bit 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.Cyberspace on GitHub.

Use this code every bit an easy way to get up and running in but a few minutes. The project is saved as a Microsoft Visual Studio 2017 project, but is compatible with any .Cyberspace 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'due 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 Pb

Christian builds software for the health manufacture and leads upwards a team. 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 political party sources.