Top
ArticleCity.comArticle Categories Use C# to Open & Write an Excel File in .Net

Use C# to Open & Write an Excel File in .Net

Originally posted on https://ironsoftware.com/csharp/excel/tutorials/csharp-open-write-excel-file/

 

How to open an Excel file in C#

  1. Install 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

Install the Excel Library to your Visual Studio Project

IronXL.Excel provides a versatile, advanced, and efficient library for opening, reading, editing and saving Excel files in .NET.

The first step will be to install IronXL.Excel, and this is most easily achieved using our NuGet package, although you may also choose to manually install the DLL to your project or to your global assembly cache.

PM > Install-Package IronXL.Excel

Open an Excel File

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

Write and Save Changes to the Excel File

  1. sheet["B1"].Value = 11.54;
  2. //Save Changes
  3. workbook.SaveAs("test.xlsx");

Summary

In summary, IronXL.Excel is a stand alone .Net software library library for reading a wide range of spreadsheet formats. It does not require Microsoft Excel to be installed, nor depend on Interop.

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.

Our Object Reference with specific reference to the WorkBook class.

No Comments

Sorry, the comment form is closed at this time.