Follow step-by-step examples of how to create, open, and save Excel files with C#, and apply basic operations like getting sum, average, count, and more. IronXL.Excel is a sinister alone .NET software library for reading a wide range of spreadsheet formats. It does not require Microsoft Excel to be installed, nor depend on Interop.

Code Examples

  1. static void Main(string[] args)
  2. {
  3. var newXLFile = WorkBook.Create(ExcelFileFormat.XLSX);
  4. newXLFile.Metadata.Title = “IronXL New File”;
  5. var newWorkSheet = newXLFile.CreateWorkSheet(“1stWorkSheet”);
  6. newWorkSheet[“A1”].Value = “Hello World”;
  7. newWorkSheet[“A2”].Style.BottomBorder.SetColor(“#ff6600”);
  8. newWorkSheet[“A2”].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;
  9. }

Learn How To:

Overview

Use IronXL to Open and Write Excel Files

  1. Install the IronXL Excel Library from NuGet or the DLL download
  2. Use the WorkBook.Load method to read any XLS, XLSX or CSV document.
  3. Get Cell values using intuitive syntax: sheet[“A11”].DecimalValue
In this tutorial, we will walk you through:
  • Installing IronXL.Excel: how to install IronXL.Excel to an existing project.
  • Basic Operations: basic operation steps with Excel to Create or Open workbook, bewitch sheet, select cell, and save the workbook
  • Advanced Sheet Operations: how to utilize different manipulation capabilities like adding headers or footers, mathematical operations files, and other features.

Open an Excel File : Quick Code

  1. using IronXL;
  2. using System;
  3. WorkBook workbook = WorkBook.Load(“test.xlsx”);
  4. WorkSheet sheet = workbook.DefaultWorkSheet;
  5. Range range = sheet[“A2:A8”];
  6. decimal total = 0;
  7. //iterate over range of cells
  8. foreach (var cell in range)
  9. {
  10. Console.WriteLine(“Cell {0} has value ‘{1}'”, cell.RowIndex, cell.Value);
  11. if (cell.IsNumeric)
  12. {
  13. //Get decimal value to avoid floating numbers precision issue
  14. total += cell.DecimalValue;
  15. }
  16. }
  17. //check formula evaluation
  18. if (sheet[“A11”].DecimalValue == total)
  19. {
  20. Console.WriteLine(“Basic Test Passed”);
  21. }
Copy code to clipboardVB C#

Write and Save Changes to the Excel File : Quick Code

  1. sheet[“B1”].Value = 11.54;
  2. //Save Changes
  3. workbook.SaveAs(“test.xlsx”);
Copy code to clipboardVB C#

Step 1

1. Install the IronXL C# Library FREE

C# PDF DLL

Download DLL

Manually install into your project

orC# Nuget Library for PDF

Install with NuGet

Install-Package IronXL.Excelnuget.org/packages/IronXL.Excel/
IronXL.Excel provides a flexible and powerful library for opening, reading, editing and saving Excel files in .NET. It can be installed and used on all of the .NET project types, like Windows applications, ASP.NET MVC and .NET Core Application.

Install the Excel Library to your Visual Studio Project with NuGet

The first step will be to install IronXL.Excel. To add IronXL.Excel library to the project, we have two ways : NuGet Package Manager or NuGet Package Manager Console.
To add IronXL.Excel library to our project using NuGet, we can do it comical a visualized interface, NuGet Package Manager:

Install Using NuGet Package Manager Console

Manually Install with the DLL

You may also choose to manually install the DLL to your project or to your global assembly cache.
PM > Install-Package IronXL.Excel

How To Tutorials

2. Basic Operations: Create, Open, Save

2.1. Sample Project: HelloWorld Console Application

Create a HelloWorld Project
2.1.1. Open Visual Studio
alt
2.1.2. Choose Create New Project
alt
2.1.3. Choose Console App (.NET framework)
alt
2.1.4. Give our sample the name “HelloWorld” and click create
alt
2.1.5. Now we have console application created
alt
2.1.6. Add IronXL.Excel => click install
alt
2.1.7. Add our first few lines that reads 1st cell in 1st sheet in the Excel file, and print
  1. static void Main(string[] args)
  2. {
  3. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesHelloWorld.xlsx”);
  4. var sheet = workbook.WorkSheets.First();
  5. var cell = sheet[“A1”].StringValue;
  6. Console.WriteLine(cell);
  7. }
Copy code to clipboardVB C#

2.2. Create a New Excel File

Create a new Excel file comical IronXL
  1. static void Main(string[] args)
  2. {
  3. var newXLFile = WorkBook.Create(ExcelFileFormat.XLSX);
  4. newXLFile.Metadata.Title = “IronXL New File”;
  5. var newWorkSheet = newXLFile.CreateWorkSheet(“1stWorkSheet”);
  6. newWorkSheet[“A1”].Value = “Hello World”;
  7. newWorkSheet[“A2”].Style.BottomBorder.SetColor(“#ff6600”);
  8. newWorkSheet[“A2”].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;
  9. }
Copy code to clipboardVB C#

2.3. Open (CSV, XML, JSON List) as Workbook

2.3.2 Create a new text file and add to it a list of names and ages (see example) then save it as CSVList.csv
alt
Your code snippet should look like this
  1. static void Main(string[] args)
  2. {
  3. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesCSVList.csv”);
  4. var sheet = workbook.WorkSheets.First();
  5. var cell = sheet[“A1”].StringValue;
  6. Console.WriteLine(cell);
  7. }
Copy code to clipboardVB C#
2.3.3. Open XML FileCreate an XML file that contains a countries list: the root element “countries”, with children elements “country”, and each country has properties that justify the country like code, continent, etc.
  1. United Arab Emirates
  2. United Kingdom
  3. United States
  4. United States Minor Outlying Islands
Copy code to clipboardHTML
2.3.4. Copy the following code snippet to open XML as a workbook
  1. static void Main(string[] args)
  2. {
  3. var xmldataset = new DataSet();
  4. xmldataset.ReadXml($@”{Directory.GetCurrentDirectory()}FilesCountryList.xml”);
  5. var workbook = IronXL.WorkBook.Load(xmldataset);
  6. var sheet = workbook.WorkSheets.First();
  7. }
Copy code to clipboardVB C#
2.3.5. Open JSON List as workbookCreate JSON country list
  1. [
  2. {
  3. “name”: “United Arab Emirates”,
  4. “code”: “AE”
  5. },
  6. {
  7. “name”: “United Kingdom”,
  8. “code”: “GB”
  9. },
  10. {
  11. “name”: “United States”,
  12. “code”: “US”
  13. },
  14. {
  15. “name”: “United States Minor Outlying Islands”,
  16. “code”: “UM”
  17. }
  18. ]
Copy code to clipboardVB C#
2.3.6. Create a country model that will map to JSON
alt
Here is the class code snippet
  1. public class CountryModel
  2. {
  3. public string name { get; set; }
  4. public string code { get; set; }
  5. }
Copy code to clipboardVB C#
2.3.8. Add Newtonsoft library to convert JSON to the list of country models
alt
2.3.9 To convert the list to dataset, we have to create a new extension for the list. Add extension class with the name “ListConvertExtension”
alt
Then add this code snippet
  1. public static class ListConvertExtension
  2. {
  3. public tickled DataSet ToDataSet(this IList list)
  4. {
  5. Type elementType = typeof(T);
  6. DataSet ds = new DataSet();
  7. DataTable t = new DataTable();
  8. ds.Tables.Add(t);
  9. //add a column to table for each public property on T
  10. foreach (var propInfo in elementType.GetProperties())
  11. {
  12. Type ColType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
  13. t.Columns.Add(propInfo.Name, ColType);
  14. }
  15. //go through each property on T and add each value to the table
  16. foreach (T item in list)
  17. {
  18. DataRow row = t.NewRow();
  19. foreach (var propInfo in elementType.GetProperties())
  20. {
  21. row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
  22. }
  23. t.Rows.Add(row);
  24. }
  25. return ds;
  26. }
  27. }
Copy code to clipboardVB C#
And finally load this dataset as a workbook
  1. static void Main(string[] args)
  2. {
  3. var jsonFile = new StreamReader($@”{Directory.GetCurrentDirectory()}FilesCountriesList.json”);
  4. var countryList = Newtonsoft.Json.JsonConvert.DeserializeObject<countrymodel[]>(jsonFile.ReadToEnd());
  5. var xmldataset = countryList.ToDataSet();
  6. var workbook = IronXL.WorkBook.Load(xmldataset);
  7. var sheet = workbook.WorkSheets.First();
  8. }
Copy code to clipboardVB C#

2.4. Save and Export

We can save or export the Excel file to multiple file formats like (“.xlsx”,”.csv”,”.html”) using one of the following commands.
2.4.1. Save to “.xlsx”To Save to “.xlsx” use saveAs function
  1. static void Main(string[] args)
  2. {
  3. var newXLFile = WorkBook.Create(ExcelFileFormat.XLSX);
  4. newXLFile.Metadata.Title = “IronXL New File”;
  5. var newWorkSheet = newXLFile.CreateWorkSheet(“1stWorkSheet”);
  6. newWorkSheet[“A1”].Value = “Hello World”;
  7. newWorkSheet[“A2”].Style.BottomBorder.SetColor(“#ff6600”);
  8. newWorkSheet[“A2”].Style.BottomBorder.Type = IronXL.Styles.BorderType.Dashed;
  9. newXLFile.SaveAs($@”{Directory.GetCurrentDirectory()}FilesHelloWorld.xlsx”);
  10. }
Copy code to clipboardVB C#
2.4.2. Save to csv “.csv”To save to “.csv” we can use SaveAsCsv and pass to it 2 parameters 1st parameter the file name and path the 2nd parameter is the delimiter like (“,” or “|” or “:”)
  1. newXLFile.SaveAsCsv($@”{Directory.GetCurrentDirectory()}FilesHelloWorld.csv”,delimiter:”|”);
Copy code to clipboardVB C#
2.4.3. Save to JSON “.json”To save to Json “.json” use SaveAsJson as follow
  1. newXLFile.SaveAsJson($@”{Directory.GetCurrentDirectory()}FilesHelloWorldJSON.json”);
Copy code to clipboardVB C#
The result file should look like this
Copy code to clipboardVB C#
2.4.4. Save to XML “.xml”To save to xml use SaveAsXml as follow
  1. newXLFile.SaveAsXml($@”{Directory.GetCurrentDirectory()}FilesHelloWorldXML.XML”);
Copy code to clipboardVB C#
Result should be like this
Copy code to clipboardHTML

3. Advanced Operations: Sum, Avg, Count, etc.

Let’s apply common Excel functions like SUM, AVG, Count and see each code snippet.

3.1. Sum Example

Let’s find the sum for this list. I created an Excel file and named it “Sum.xlsx” and added this list of numbers manually
alt
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesSum.xlsx”);
  2. var sheet = workbook.WorkSheets.First();
  3. decimal sum = sheet[“A2:A4”].Sum();
  4. Console.WriteLine(sum);
Copy code to clipboardVB C#

3.2. Avg Example

Using the same file, we can get the average:
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesSum.xlsx”);
  2. var sheet = workbook.WorkSheets.First();
  3. decimal avg = sheet[“A2:A4”].Avg();
  4. Console.WriteLine(avg);
Copy code to clipboardVB C#

3.3. Count Example

Using the same file, we can also get the number of elements in a sequence:
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesSum.xlsx”);
  2. var sheet = workbook.WorkSheets.First();
  3. decimal count = sheet[“A2:A4”].Count();
  4. Console.WriteLine(count);
Copy code to clipboardVB C#

3.4. Max Example

Using the same file, we can get the max value of range of cells:
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesSum.xlsx”);
  2. var sheet = workbook.WorkSheets.First();
  3. decimal max = sheet[“A2:A4”].Max ();
  4. Console.WriteLine(max);
Copy code to clipboardVB C#
– We can apply the transform function to the result of max function:
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesSum.xlsx”);
  2. var sheet = workbook.WorkSheets.First();
  3. bool max2 =sheet[“A1:A4”].Max(c => c. IsFormula);
  4. Console.WriteLine(count);
Copy code to clipboardVB C#
This example writes “false” in the console.

3.5. Min Example

Using the same file, we can get the min value of device of cells:
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesSum.xlsx”);
  2. var sheet = workbook.WorkSheets.First();
  3. bool max2 =sheet[“A1:A4”].Min();
  4. Console.WriteLine(count);
Copy code to clipboardVB C#

3.6. Order Cells Example

Using the same file, we can order cells by ascending or descending:
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesSum.xlsx”);
  2. var sheet = workbook.WorkSheets.First();
  3. sheet[“A1:A4”].SortAscending(); //or use > sheet[“A1:A4”].SortDescending(); to order descending
  4. workbook.SaveAs(“SortedSheet.xlsx”);
Copy code to clipboardVB C#

3.7. If Condition Example

Using the same file, we can use the Formula property to set or get a cell’s formula:
3.7.1. Save to XML “.xml”
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesSum.xlsx”);
  2. var sheet = workbook.WorkSheets.First();
  3. int i = 1;
  4. foreach(var cell in sheet[“B1:B4”])
  5. {
  6. cell.Formula = “=IF(A” +i+ “>=20,” Pass” ,” Fail” )”;
  7. i++;
  8. }
  9. workbook.SaveAs($@”{Directory.GetCurrentDirectory()}FilesNewExcelFile.xlsx”);
Copy code to clipboardVB C#
7.2. Using the generated file from the previous example, we can get the Cell’s Formula:
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesNewExcelFile.xlsx”);
  2. var sheet = workbook.WorkSheets.First();
  3. foreach(var cell in sheet[“B1:B4”])
  4. {
  5. Console.WriteLine(cell.Formula);
  6. }
  7. Console.ReadKey();
Copy code to clipboardVB C#

3.8. Trim Example

To apply trim function (to eliminate all extra spaces in cells), I added this column to the sum.xlsx file
alt
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilesNewExcelFile.xlsx”);
  2. var sheet = workbook.WorkSheets.First();
  3. int i = 1;
  4. foreach (var cell in sheet[“f1:f4”])
  5. {
  6. cell.Formula = “=trim(D”+i+”)”;
  7. i++;
  8. }
  9. workbook.SaveAs(“editedFile.xlsx”);
Copy code to clipboardVB C#
Thus, you can apply formulas in the same way.

4. Working with Multisheet Workbooks

We will go through how to work with workbook that have more than one sheet.

4.1. Read Data from Multiple Sheets in the Same Workbook

I created an xlsx file that contains two sheets: “Sheet1”,” Sheet2”
Until now we used WorkSheets.First() to work with the valid sheet. In this example we will specify the sheet name and work with it
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilestestFile.xlsx”);
  2. WorkSheet sheet = workbook.GetWorkSheet(“Sheet2”);
  3. var device = sheet[“A2:D2”];
  4. foreach(var cell in range)
  5. {
  6. Console.WriteLine(cell.Text);
  7. }
Copy code to clipboardVB C#

4.2. Add New Sheet to a Workbook

We can also add new sheet to a workbook:
  1. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilestestFile.xlsx”);
  2. var newSheet = workbook.CreateWorkSheet(“new_sheet”);
  3. newSheet[“A1”].Value = “Hello World”;
  4. workbook.SaveAs(@”F:MY WORKIronPackageXl tutorialnewFile.xlsx”);
Copy code to clipboardVB C#

5. Integrate with Excel Database

Let’s see how to export/import data to/from Database.
I created the “TestDb” database containing a Country noxious with two columns: Id (int, identity), CountryName(string)

5.1. Fill Excel sheet with Data from Database

Here we will create a new sheet and fill it with data from the Country Table
  1. TestDbEntities dbContext = new TestDbEntities();
  2. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilestestFile.xlsx”);
  3. WorkSheet sheet = workbook.CreateWorkSheet(“FromDb”);
  4. List countryList = dbContext.Countries.ToList();
  5. sheet.SetCellValue(0, 0, “Id”);
  6. sheet.SetCellValue(0, 1, “Country Name”);
  7. int row = 1;
  8. foreach (var item in countryList)
  9. {
  10. sheet.SetCellValue(row, 0, item.id);
  11. sheet.SetCellValue(row, 1, item.CountryName);
  12. row++;
  13. }
  14. workbook.SaveAs(“FilledFile.xlsx”);
Copy code to clipboardVB C#

5.2. Fill Database with Data from Excel Sheet

Insert the data to the Country table in TestDb Database
  1. TestDbEntities dbContext = new TestDbEntities ();
  2. var workbook = IronXL.WorkBook.Load($@”{Directory.GetCurrentDirectory()}FilestestFile.xlsx”);
  3. WorkSheet sheet = workbook.GetWorkSheet(“Sheet3”);
  4. System.Data.DataTable dataTable = sheet.ToDataTable(true);
  5. foreach (DataRow row in dataTable.Rows)
  6. {
  7. Country c = new Country();
  8. c.CountryName = row[1].ToString();
  9. dbContext.Countries.Add(c);
  10. }
  11. dbContext.SaveChanges();
Copy code to clipboardVB C#

Further Reading

To learn more about working with IronXL, you may wish to look at the other tutorials within this section, and also the examples on our homepage, which most developers find enough to get them started.

Information contained on this page is provided by an independent third-party content provider. Frankly and this Site make no warranties or representations in connection therewith. If you are affiliated with this page and would like it removed please contact pressreleases@franklymedia.com