How To Open Excel File In C# Windows Application
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 Web APIs, and modifying formulae within the spreadsheet. This commodity references the IronXL code samples, which is a .NET Cadre Panel App.
Reading and creating Excel files in C# and all other .NET languages is easy using the IronXL software library.
Information technology does non crave Excel to be installed on your server or Interop. IronXL provides a faster and more intuitive API than Microsoft.Office.Interop.Excel.
Overview
How to Read Excel File in C#
- Download the C# Library to read Excel files
- Load and read an Excel file (workbook)
- Create an Excel workbook in CSV or XLSX
- Edit jail cell values in a range of cells
- Validate spreadsheet data
- Consign 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.
- Install the IronXL Excel Library. We can practice this using our NuGet package or by downloading the .Net Excel DLL.
- Employ the WorkBook.Load method to read any XLS, XLSX or CSV document.
- Get Cell values using intuitive syntax:
sheet["A11"].DecimalValue
IronXL Includes:
- Dedicated production support from our .Cyberspace engineers
- Easy installation via Microsoft Visual Studio
- 30 day free trial test for development. Licenses from $499.
We will see how like shooting fish in a barrel it is to read Excel files in C# or VB.Net using the IronXL library. The samples comprise 3 Excel sheets.
Read XLS or XLSX Files: Quick Code
In this instance we tin meet how to read the excel file efficiently without Interop in C#. The final Avant-garde Operations prove Linq compatibility and aggregate range mathematics.
/** 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("exam.xlsx"); WorkSheet sheet = workbook.WorkSheets.First(); //Select cells hands in Excel notation and return the calculated value int cellValue = canvass["A2"].IntValue; // Read from Ranges of cells elegantly. foreach (var cell in sheet["A2:A10"]) { Console.WriteLine("Prison cell {0} has value '{1}'", cell.AddressString, jail cell.Text); } ///Advanced Operations //Calculate amass values such as Min, Max and Sum decimal sum = canvass["A2:A10"].Sum(); //Linq compatible decimal max = sheet["A2:A10"].Max(c => c.DecimalValue);
/** Read XLS or XLSX File anchor-read-an-xls-or-xlsx-file **/ using IronXL; using Organisation.Linq; //Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV WorkBook workbook = WorkBook.Load("examination.xlsx"); WorkSheet sheet = workbook.WorkSheets.Get-go(); //Select cells easily in Excel notation and return the calculated value int cellValue = sheet["A2"].IntValue; // Read from Ranges of cells elegantly. foreach (var cell in sail["A2:A10"]) { Console.WriteLine("Jail cell {0} has value '{1}'", jail cell.AddressString, cell.Text); } ///Advanced Operations //Calculate aggregate values such as Min, Max and Sum decimal sum = sheet["A2:A10"].Sum(); //Linq compatible 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 Equally WorkBook = WorkBook.Load("test.xlsx") Private sheet As WorkSheet = workbook.WorkSheets.First() 'Select cells hands in Excel notation and return the calculated value Individual cellValue Every bit Integer = sheet("A2").IntValue ' Read from Ranges of cells elegantly. For Each jail cell In sail("A2:A10") Console.WriteLine("Cell {0} has value '{ane}'", cell.AddressString, cell.Text) Adjacent cell '''Advanced Operations 'Calculate aggregate values such as Min, Max and Sum Dim sum Equally Decimal = sheet("A2:A10").Sum() 'Linq compatible Dim max As Decimal = sheet("A2:A10").Max(Function(c) c.DecimalValue)
VB C#
Step 1
i. Download the IronXL C# Library for FREE
Download DLL
or
Install with NuGet
Install-Packet IronXL.Excel
nuget.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 as well cull to manually install the DLL to your project or to your global assembly cache.
Installing the IronXL Nuget Bundle
- In Visual Studio, correct-click on the project select "Manage Nuget Packages ..."
- Search for the IronXL.Excel packet and install
Another mode to install is:
- Enter the Package Manager Console
- 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 Tutorials
2. Load a WorkBook
The WorkBook
form represents an Excel sheet. To open an Excel File using C#, we use WorkBook.Load and specify the path of the Excel file (.xlsx).
/** Load WorkBook anchor-load-a-workbook **/ var workbook = WorkBook.Load(@"Spreadsheets\\Gdp.xlsx");
/** Load WorkBook ballast-load-a-workbook **/ var workbook = WorkBook.Load(@"Spreadsheets\\Gdp.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 represent worksheets in the Excel document. If the sheet 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
three. 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 '''anchor-create-a-workbook '''* Dim workbook Equally New WorkBook(ExcelFileFormat.XLSX)
VB C#
Sample: ApiToExcelProcessor
Annotation: Utilise ExcelFileFormat.XLS for legacy for Microsoft Excel spreadsheets (95 and before).
4. Create a WorkSheet
Each "WorkBook" can accept multiple WorkSheets. A "WorkSheet" is a sheet of information, while a WorkBook represents a collection of WorkSheets. This is how 1 workbook with 2 worksheets looks in Excel.
To create a new WorkSheet telephone call WorkBook.CreateWorkSheet
and pass the proper noun of the worksheet.
var worksheet = workbook.CreateWorkSheet("Countries");
var worksheet = workbook.CreateWorkSheet("Countries");
Dim worksheet = workbook.CreateWorkSheet("Countries")
VB C#
5. Become Cell Range
The "Range" course represents a two-dimensional collection of "Prison cell" objects. It represents a literal range of Excel cells. Obtain ranges by using the string indexer on a WorkSheet object.
The statement text is either the coordinate of a jail cell (eastward.m. "A1") or a span of cells from left to correct top to bottom (e.one thousand. "B2:E5"). It is likewise 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
vi. Edit Cell Values Within a Range
There are several ways to read or edit the values of cells inside a Range. If the count is known, use a For loop.
/** Edit Cell Values in Range anchor-edit-cell-values-within-a-range **/ //Iterate through the rows for (var y = 2; y <= 101; y++) { var result = new PersonValidationResult { Row = y }; results.Add(event); //Become all cells for the person var cells = worksheet[$"A{y}:E{y}"].ToList(); //Validate the telephone number (1 = B) var phoneNumber = cells[1].Value; result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber); //Validate the electronic mail address (iii = D) result.EmailErrorMessage = ValidateEmailAddress((string)cells[three].Value); //Get the raw date in the format of Calendar month Day[suffix], Year (4 = E) var rawDate = (string)cells[4].Value; issue.DateErrorMessage = ValidateDate(rawDate); }
/** Edit Cell Values in Range ballast-edit-cell-values-within-a-range **/ //Iterate through the rows for (var y = two; y <= 101; y++) { var result = new PersonValidationResult { Row = y }; results.Add(event); //Get all cells for the person var cells = worksheet[$"A{y}:Eastward{y}"].ToList(); //Validate the phone number (1 = B) var phoneNumber = cells[1].Value; event.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 Calendar month Day[suffix], Yr (4 = E) var rawDate = (cord)cells[4].Value; result.DateErrorMessage = ValidateDate(rawDate); }
''' '''Edit Cell Values in Range '''anchor-edit-prison cell-values-inside-a-range '''* 'Iterate through the rows For y = two To 101 Dim upshot = New PersonValidationResult With {.Row = y} results.Add(event) 'Get all cells for the person Dim cells = worksheet($"A{y}:E{y}").ToList() 'Validate the phone number (one = B) Dim phoneNumber = cells(1).Value upshot.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber)) 'Validate the email accost (iii = D) result.EmailErrorMessage = ValidateEmailAddress(CStr(cells(3).Value)) 'Get the raw date in the format of Month Day[suffix], Year (4 = E) Dim rawDate = CStr(cells(iv).Value) result.DateErrorMessage = ValidateDate(rawDate) Next y
VB C#
Sample: DataValidation
7. Validate Spreadsheet Data
Use IronXL to validate a sheet of data. The DataValidation sample uses libphonenumber-csharp
to validate telephone 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 result = new PersonValidationResult { Row = i }; results.Add(issue); //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; outcome.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber); //Validate the electronic mail address (3 = D) outcome.EmailErrorMessage = ValidateEmailAddress((string)cells[iii].Value); //Get the raw date in the format of Month 24-hour interval[suffix], Year (iv = E) var rawDate = (cord)cells[4].Value; result.DateErrorMessage = ValidateDate(rawDate); }
/** Validate Spreadsheet Information anchor-validate-spreadsheet-data **/ //Iterate through the rows for (var i = 2; i <= 101; i++) { var outcome = new PersonValidationResult { Row = i }; results.Add together(event); //Get all cells for the person var cells = worksheet[$"A{i}:East{i}"].ToList(); //Validate the telephone number (ane = B) var phoneNumber = cells[1].Value; upshot.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, (string)phoneNumber); //Validate the electronic mail address (3 = D) event.EmailErrorMessage = ValidateEmailAddress((string)cells[three].Value); //Get the raw appointment in the format of Month Day[suffix], Year (four = Due east) var rawDate = (string)cells[four].Value; upshot.DateErrorMessage = ValidateDate(rawDate); }
''' '''Validate Spreadsheet Data '''anchor-validate-spreadsheet-data '''* 'Iterate through the rows For i = 2 To 101 Dim result = New PersonValidationResult With {.Row = i} results.Add(event) 'Get all cells for the person Dim cells = worksheet($"A{i}:Due east{i}").ToList() 'Validate the telephone number (1 = B) Dim phoneNumber = cells(1).Value result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber)) 'Validate the e-mail address (3 = D) event.EmailErrorMessage = ValidateEmailAddress(CStr(cells(three).Value)) 'Get the raw date in the format of Month Solar day[suffix], Yr (4 = E) Dim rawDate = CStr(cells(four).Value) event.DateErrorMessage = ValidateDate(rawDate) Next i
VB C#
The higher up code loops through each row in the spreadsheet and grabs the cells every bit a list. Each validates method checks the value of a cell and returns an mistake bulletin if the value is invalid.
This code creates a new sail, specifies headers, and outputs the error message results then 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 = "Email Error"; resultsSheet["E1"].Value = "Engagement Error"; for (var i = 0; i < results.Count; i++) { var issue = results[i]; resultsSheet[$"A{i + 2}"].Value = result.Row; resultsSheet[$"B{i + two}"].Value = upshot.IsValid ? "Yes" : "No"; resultsSheet[$"C{i + two}"].Value = result.PhoneNumberErrorMessage; resultsSheet[$"D{i + 2}"].Value = result.EmailErrorMessage; resultsSheet[$"Due 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 = "Engagement Error"; for (var i = 0; i < results.Count; i++) { var issue = results[i]; resultsSheet[$"A{i + 2}"].Value = result.Row; resultsSheet[$"B{i + 2}"].Value = result.IsValid ? "Yep" : "No"; resultsSheet[$"C{i + 2}"].Value = effect.PhoneNumberErrorMessage; resultsSheet[$"D{i + 2}"].Value = effect.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 = "Telephone Error" resultsSheet("D1").Value = "E-mail Error" resultsSheet("E1").Value = "Engagement Error" 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, "Yeah", "No") resultsSheet($"C{i + 2}").Value = result.PhoneNumberErrorMessage resultsSheet($"D{i + 2}").Value = upshot.EmailErrorMessage resultsSheet($"E{i + 2}").Value = result.DateErrorMessage Adjacent i workbook.SaveAs("Spreadsheets\\PeopleValidated.xlsx")
VB C#
8. Export Information 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 land and 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 yous to create a model object that can export information to the database.
public class Country { [Fundamental] public Guid Key { go; set up; } public cord Name { go; set; } public decimal GDP { become; set; } }
public class Land { [Key] public Guid Key { get; prepare; } public string Name { get; gear up; } public decimal Gross domestic product { go; set up; } }
Public Class Land <Key> Public Property Fundamental() Every bit Guid Public Belongings Name() As String Public Property GDP() As Decimal Cease Class
VB C#
To use a different database, install the corresponding NuGet bundle and observe the equivalent of UseSqLite()
/** Consign Data using Entity Framework anchor-export-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($"Data Source=Country.db"); connectedness.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); } }
/** Consign Data using Entity Framework anchor-export-information-using-entity-framework **/ public class CountryContext : DbContext { public DbSet<State> Countries { get; prepare; } public CountryContext() { //TODO: Make async Database.EnsureCreated(); } /// <summary> /// Configure context to utilise Sqlite /// </summary> /// <param proper noun="optionsBuilder"></param> protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { var connectedness = new SqliteConnection($"Information Source=Country.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(connexion); base.OnConfiguring(optionsBuilder); } }
''' '''Export Information using Entity Framework '''ballast-export-information-using-entity-framework '''* Public Grade CountryContext Inherits DbContext Public Property Countries() As DbSet(Of State) Public Sub New() 'TODO: Brand async Database.EnsureCreated() End Sub ''' <summary> ''' Configure context to use Sqlite ''' </summary> ''' <param name="optionsBuilder"></param> Protected Overrides Sub OnConfiguring(ByVal optionsBuilder As DbContextOptionsBuilder) Dim connexion = New SqliteConnection($"Data Source=Land.db") connection.Open() Dim command = connection.CreateCommand() 'Create the database if it doesn't already exist control.CommandText = $"PRAGMA foreign_keys = ON;" control.ExecuteNonQuery() optionsBuilder.UseSqlite(connection) MyBase.OnConfiguring(optionsBuilder) End Sub Finish Class
VB C#
Create a CountryContext
, iterate through the range to create each record, and then SaveAsync
to commit data to the database
public async Job ProcessAsync() { //Get 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 = 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[ane].Value }; //Add together the entity wait countryContext.Countries.AddAsync(country); } //Commit changes to the database await countryContext.SaveChangesAsync(); } }
public async Task ProcessAsync() { //Get the outset 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 = ii; i <= 213; i++) { //Go the range from A-B var range = worksheet[$"A{i}:B{i}"].ToList(); //Create a Country entity to exist saved to the database var country = new Country { Proper name = (string)range[0].Value, Gdp = (decimal)(double)range[1].Value }; //Add the entity expect countryContext.Countries.AddAsync(country); } //Commit changes to the database await countryContext.SaveChangesAsync(); } }
Public Async Office ProcessAsync() Every bit Task 'Get the first worksheet Dim workbook = WorkBook.Load("Spreadsheets\\Gross domestic product.xlsx") Dim worksheet = workbook.GetWorkSheet("GDPByCountry") 'Create the database connection Using countryContext As New CountryContext() 'Iterate through all the cells For i = 2 To 213 'Become 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 Land With { .Name = CStr(range(0).Value), .GDP = CDec(CDbl(range(i).Value)) } 'Add the entity Await countryContext.Countries.AddAsync(country) Next i 'Commit changes to the database Wait countryContext.SaveChangesAsync() End Using End Part
VB C#
Sample: ExcelToDB
9. Add together Formula to a Spreadsheet
Set formula of Cell
'due south with the Formula
property.
The code below iterates through each state and puts a pct full in column C.
/** Add Spreadsheet Formulae ballast-add-formulae-to-a-spreadsheet **/ //Iterate through all rows with a value for (var y = 2; y < i; y++) { //Get the C cell var jail cell = canvass[$"C{y}"].First(); //Set the formula for the Percent 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 for (var y = two; y < i; y++) { //Get the C cell var cell = sheet[$"C{y}"].First(); //Gear up the formula for the Percentage of Full column cell.Formula = $"=B{y}/B{i}"; }
''' '''Add Spreadsheet Formulae '''ballast-add-formulae-to-a-spreadsheet '''* 'Iterate through all rows with a value Dim y = 2 Do While y < i 'Become the C prison cell Dim cell = sheet($"C{y}").First() 'Set the formula for the Percentage of Total column cell.Formula = $"=B{y}/B{i}" y += 1 Loop
VB C#
Sample: AddFormulaeProcessor
ten. Download Information from an API to Spreadsheet
The following call makes a REST call with RestClient.Internet. Information technology downloads JSON and converts it into a "List" of the blazon RestCountry
. It is then easy to iterate through each country and save the data from the Residuum API to an Excel spreadsheet.
/** Data API to Spreadsheet anchor-download-data-from-an-api-to-spreadsheet **/ var customer = new Client(new Uri("https://restcountries.eu/rest/v2/")); List<RestCountry> countries = look customer.GetAsync<List<RestCountry>>();
/** Data API to Spreadsheet anchor-download-information-from-an-api-to-spreadsheet **/ var client = new Customer(new Uri("https://restcountries.eu/rest/v2/")); List<RestCountry> countries = look client.GetAsync<List<RestCountry>>();
''' '''Data API to Spreadsheet '''anchor-download-information-from-an-api-to-spreadsheet '''* Dim client As New Client(New Uri("https://restcountries.eu/residue/v2/")) Dim countries As List(Of RestCountry) = Look customer.GetAsync(Of Listing(Of RestCountry))()
VB C#
Sample: ApiToExcel
This is what the API JSON data looks like.
The following lawmaking iterates through the countries and sets the Name, Population, Region, NumericCode, and Summit iii Languages in the spreadsheet.
for (var i = ii; i < countries.Count; i++) { var state = countries[i]; //Gear up the basic values worksheet[$"A{i}"].Value = land.proper name; worksheet[$"B{i}"].Value = country.population; worksheet[$"1000{i}"].Value = country.region; worksheet[$"H{i}"].Value = land.numericCode; //Iterate through languages for (var x = 0; x < iii; x++) { if (x > (land.languages.Count - 1)) intermission; var linguistic communication = land.languages[x]; //Get the letter for the cavalcade var columnLetter = GetColumnLetter(4 + 10); //Set up the linguistic communication name worksheet[$"{columnLetter}{i}"].Value = language.name; } }
for (var i = 2; i < countries.Count; i++) { var state = countries[i]; //Set the bones values worksheet[$"A{i}"].Value = land.proper noun; worksheet[$"B{i}"].Value = state.population; worksheet[$"K{i}"].Value = country.region; worksheet[$"H{i}"].Value = state.numericCode; //Iterate through languages for (var x = 0; x < iii; 10++) { if (x > (country.languages.Count - one)) break; var linguistic communication = country.languages[x]; //Get the letter for the column var columnLetter = GetColumnLetter(iv + x); //Set the language name worksheet[$"{columnLetter}{i}"].Value = linguistic communication.proper name; } }
For i = two To countries.Count - 1 Dim country = countries(i) 'Set the bones values worksheet($"A{i}").Value = state.name worksheet($"B{i}").Value = country.population worksheet($"G{i}").Value = state.region worksheet($"H{i}").Value = country.numericCode 'Iterate through languages For ten = 0 To ii If x > (country.languages.Count - 1) Then Exit For Finish If Dim language = country.languages(x) 'Get the alphabetic character for the cavalcade Dim columnLetter = GetColumnLetter(iv + x) 'Ready the language name worksheet($"{columnLetter}{i}").Value = language.proper noun Next 10 Adjacent i
VB C#
Object Reference and Resources
You may also find the IronXL grade documentation inside the Object Reference of great value.
In improver, 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 lone .Net software library for reading a wide variety of spreadsheet formats. Information technology does not require Microsoft Excel to be installed, and is not dependant on Interop.
Tutorial Quick Access
Download this Tutorial as C# Source Lawmaking
The full free C# for Excel Source Lawmaking for this tutorial is bachelor to download as a zipped Visual Studio 2017 project file.
Download
Explore this Tutorial on GitHub
The source code for this project is bachelor in C# and VB.NET on GitHub.
Utilize this code as an like shooting fish in a barrel way to get up and running in only a few minutes. The project is saved equally a Microsoft Visual Studio 2017 project, but 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's features, namespaces, classes, methods fields and enums.
View the API Reference
Source: https://ironsoftware.com/csharp/excel/tutorials/how-to-read-excel-file-csharp/
Posted by: weberneart1942.blogspot.com
0 Response to "How To Open Excel File In C# Windows Application"
Post a Comment