Read excel file net

C# Read Excel File with Examples

This tutorial explains how to read an Excel file in C#, as well as perform everyday tasks like data validation, database conversion, Web API intergrations, and formula modification. This article references code examples that utilize the IronXL .NET Excel library.

IronXL facilitates reading and editing Microsoft Excel documents with C#. IronXL neither requires Microsoft Excel nor does it require Interop. In fact, IronXL provides a faster and more intuitive API than Microsoft.Office.Interop.Excel.

IronXL Includes:

  • Dedicated product support from our .NET engineers
  • Easy installation via Microsoft Visual Studio
  • 30 day free trial test for development. Licenses from $749.

Reading and creating Excel files in C# and VB.NET is easy using the IronXL software library.


Overview

How to Read Excel File in C#

  1. Download the C# Library to read Excel files
  2. Load and read an Excel file (workbook)
  3. Create an Excel workbook in CSV or XLSX
  4. Edit cell values in a range of cells
  5. Validate spreadsheet data
  6. Export data using Entity Framework

Reading .XLS and .XLSX Excel Files Using IronXL

Below is a summary of the overal workflow for reading Excel files using IronXL:

  1. Install the IronXL Excel Library. We can do this using our NuGet package or by downloading the .Net Excel DLL.
  2. Use the WorkBook.Load method to read any XLS, XLSX or CSV document.
  3. Get Cell values using intuitive syntax: sheet["A11"].DecimalValue
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-1.cs
using IronXL;
using System.Linq;
using System;

// Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();

// Select cells easily in Excel notation and return the calculated value
int cellValue = workSheet["A2"].IntValue;

// Read from Ranges of cells elegantly.
foreach (var cell in workSheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

// Advanced Operations
// Calculate aggregate values such as Min, Max and Sum
decimal sum = workSheet["A2:A10"].Sum();

// Linq compatible
decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue);
Imports IronXL
Imports System.Linq
Imports System

' Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Private workBook As WorkBook = WorkBook.Load("test.xlsx")
Private workSheet As WorkSheet = workBook.WorkSheets.First()

' Select cells easily in Excel notation and return the calculated value
Private cellValue As Integer = workSheet("A2").IntValue

' Read from Ranges of cells elegantly.
For Each cell In workSheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell

' Advanced Operations
' Calculate aggregate values such as Min, Max and Sum
Dim sum As Decimal = workSheet("A2:A10").Sum()

' Linq compatible
Dim max As Decimal = workSheet("A2:A10").Max(Function(c) c.DecimalValue)

VB   C#

The code examples used in the next sections of this tutorial (along with the sample project code) will work on three sample Excel spreadsheets (see below for a visual):


Tutorial

1. Download the IronXL C# Library for FREE

C# NuGet Library for Excel

Install with NuGet

Install-Package IronXL.Excel

nuget.org/packages/IronXL.Excel/

or

C# Excel DLL

Download DLL

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 also 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 click on the Install button to add it to the project

Another way to install the IronXL library is using the NuGet Package Manager Console:

  1. Enter the Package Manager Console
  2. Type > Install-Package IronXL.Excel

    PM > Install-Package IronXL.Excel

Additionally, you can view the package on the NuGet website

Manual Installation

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

2. Load an Excel Workbook

The WorkBook class represents an Excel sheet. To open an Excel File using C#, we use WorkBook.Load method, specifying the path of the Excel fil.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-2.cs
WorkBook workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
Dim workBook As WorkBook = WorkBook.Load("Spreadsheets\GDP.xlsx")

VB   C#

Sample: ExcelToDBProcessor

Each WorkBook can have multiple WorkSheet objects. Each one represents a single Excel worksheet in the Excel document. Use the WorkBook.GetWorkSheet method to retrieve a reference to a specific Excel worksheet.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-3.cs

Sample: ExcelToDB

Creating new Excel Documents

To create a new Excel document, construct a new WorkBook object with a valid file type.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-4.cs
WorkBook workBook = new WorkBook(ExcelFileFormat.XLSX);
Dim workBook As New WorkBook(ExcelFileFormat.XLSX)

VB   C#

Sample: ApiToExcelProcessor

Note: Use ExcelFileFormat.XLS toi support legacy versions of Microsoft Excel (95 and earlier).

Add a Worksheet to an Excel Document

As explained previously, an IronXL WorkBook contains a collection of one or more WorkSheets.

This is how one workbook with two worksheets looks in Excel.

This is how one workbook with two worksheets looks in Excel.

To create a new WorkSheet call WorkBook.CreateWorkSheet with the name of the worksheet.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-5.cs
WorkSheet workSheet = workBook.GetWorkSheet("GDPByCountry");
Dim workSheet As WorkSheet = workBook.GetWorkSheet("GDPByCountry")

VB   C#

3. Access Cell Values

Read and Edit a Single Cell

Access to the values of individual spreadsheet cells is carried out by retrieving the desired cell from its WorkSheet. as shown below:

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-16.cs
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorksheet();
IronXL.Cell cell = workSheet["B1"];
Dim workBook As WorkBook = WorkBook.Load("test.xlsx")
Dim workSheet As WorkSheet = workBook.DefaultWorksheet()
Dim cell As IronXL.Cell = workSheet("B1")

VB   C#

IronXL’s Cell class represents an invidual cell in an Excel spreadsheet. It contains properties and methods that enable users to access and modify the cell’s value directly.

Each WorkSheet object manages an index of Cell objects corresponding to every cell value in an Excel worksheet. In the source code above, we reference the desired cell by its row and column index (cell B1 in this case) using standard array indexing syntax.

With a reference to Cell object, we can read and write data to and from a spreadsheet cell:

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-17.cs
IronXL.Cell cell = workSheet["B1"];
string value = cell.StringValue;   // Read the value of the cell as a string
Console.WriteLine(value);

cell.Value = "10.3289";           // Write a new value to the cell
console.WriteLine(cell.StringValue); 
Dim cell As IronXL.Cell = workSheet("B1")
Dim value As String = cell.StringValue ' Read the value of the cell as a string
Console.WriteLine(value)

cell.Value = "10.3289" ' Write a new value to the cell
console.WriteLine(cell.StringValue)

VB   C#

Read and Write a Range of Cell Values

The Range class represents a two-dimensional collection of Cell objects. This collection refers to 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 cell (e.g. «A1», as shown previously) or a span of cells from left to right top to bottom (e.g. «B2:E5»). It is also possible to call GetRange on a WorkSheet.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-6.cs
Range range = workSheet["D2:D101"];
Dim range As Range = workSheet("D2:D101")

VB   C#

Sample: DataValidation

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

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-7.cs
// Iterate through the rows
for (var y = 2; y <= 101; y++)
{
    var result = new PersonValidationResult { Row = y };
    results.Add(result);

    // 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, (string)phoneNumber);

    // Validate the email address (3 = D)
    result.EmailErrorMessage = ValidateEmailAddress((string)cells[3].Value);

    // Get the raw date in the format of Month Day[suffix], Year (4 = E)
    var rawDate = (string)cells[4].Value;
    result.DateErrorMessage = ValidateDate(rawDate);
}
' Iterate through the rows
For y = 2 To 101
	Dim result = New PersonValidationResult With {.Row = y}
	results.Add(result)

	' Get all cells for the person
	Dim cells = workSheet($"A{y}:E{y}").ToList()

	' Validate the phone number (1 = B)
	Dim phoneNumber = cells(1).Value
	result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))

	' Validate the email address (3 = 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(4).Value)
	result.DateErrorMessage = ValidateDate(rawDate)
Next y

VB   C#

Sample: DataValidation

Add Formula to a Spreadsheet

Set formula of Cells with the Formula property.

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

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-13.cs
// Iterate through all rows with a value
for (var y = 2; y < i; y++)
{
    // Get the C cell
    Cell cell = workSheet[$"C{y}"].First();

    // Set the formula for the Percentage of Total column
    cell.Formula = $"=B{y}/B{i}";
}
' Iterate through all rows with a value
Dim y = 2
Do While y < i
	' Get the C cell
	Dim cell As Cell = workSheet($"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

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 email addresses and dates.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-8.cs
// Iterate through the rows
for (var i = 2; 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;
    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 Day[suffix], Year (4 = E)
    var rawDate = (string)cells[4].Value;
    result.DateErrorMessage = ValidateDate(rawDate);
}
' Iterate through the rows
For i = 2 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(1).Value
	result.PhoneNumberErrorMessage = ValidatePhoneNumber(phoneNumberUtil, CStr(phoneNumber))

	' Validate the email address (3 = 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(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 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.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-9.cs
var resultsSheet = workBook.CreateWorkSheet("Results");
resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";
for (var i = 0; i < results.Count; i++)
{
    var result = results[i];
    resultsSheet[$"A{i + 2}"].Value = result.Row;
    resultsSheet[$"B{i + 2}"].Value = result.IsValid ? "Yes" : "No";
    resultsSheet[$"C{i + 2}"].Value = result.PhoneNumberErrorMessage;
    resultsSheet[$"D{i + 2}"].Value = result.EmailErrorMessage;
    resultsSheet[$"E{i + 2}"].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 Error"
resultsSheet("E1").Value = "Date Error"
For i = 0 To results.Count - 1
	Dim result = results(i)
	resultsSheet($"A{i + 2}").Value = result.Row
	resultsSheet($"B{i + 2}").Value = If(result.IsValid, "Yes", "No")
	resultsSheet($"C{i + 2}").Value = result.PhoneNumberErrorMessage
	resultsSheet($"D{i + 2}").Value = result.EmailErrorMessage
	resultsSheet($"E{i + 2}").Value = result.DateErrorMessage
Next i
workBook.SaveAs("Spreadsheets\PeopleValidated.xlsx")

VB   C#

4. Export 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 can export data to the database.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-10.cs
public class Country
    {
        [Key]
        public Guid Key { get; set; }
        public string Name { get; set; }
        public decimal GDP { get; set; }
    }
Public Class Country
		<Key>
		Public Property Key() As Guid
		Public Property Name() As String
		Public Property GDP() As Decimal
End Class

VB   C#

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

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-11.cs
public class 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");
            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);
        }
    }
Public Class CountryContext
	Inherits DbContext

		Public Property Countries() As DbSet(Of Country)
		Public Sub New()
			'TODO: Make 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 connection = New SqliteConnection($"Data Source=Country.db")
			connection.Open()
			Dim command = connection.CreateCommand()
			'Create the database if it doesn't already exist
			command.CommandText = $"PRAGMA foreign_keys = ON;"
			command.ExecuteNonQuery()
			optionsBuilder.UseSqlite(connection)
			MyBase.OnConfiguring(optionsBuilder)
		End Sub
End Class

VB   C#

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

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-12.cs
public async Task ProcessAsync()
{
    //Get the first 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 country = new Country
            {
                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 Task
	'Get the first worksheet
	Dim workbook = WorkBook.Load("Spreadsheets\GDP.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
			'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(1).Value))
			}
			'Add the entity
			Await countryContext.Countries.AddAsync(country)
		Next i
		'Commit changes to the database
		Await countryContext.SaveChangesAsync()
	End Using
End Function

VB   C#

Sample: ExcelToDB

5. Download Data from an API to Spreadsheet

The following call makes a REST call with RestClient.Net. It downloads JSON and converts it into a «List» of the type RestCountry. It is then easy to iterate through each country and save the data from the REST API to an Excel spreadsheet.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-14.cs
var client = new Client(new Uri("https://restcountries.eu/rest/v2/"));
List<RestCountry> countries = await client.GetAsync<List<RestCountry>>();
Dim client As New Client(New Uri("https://restcountries.eu/rest/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 3 Languages in the spreadsheet.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-15.cs
for (var i = 2; i < countries.Count; i++)
{
    var country = countries[i];
    //Set the basic values
    workSheet[$"A{i}"].Value = country.name;
    workSheet[$"B{i}"].Value = country.population;
    workSheet[$"G{i}"].Value = country.region;
    workSheet[$"H{i}"].Value = country.numericCode;
    //Iterate through languages
    for (var x = 0; x < 3; x++)
    {
        if (x > (country.languages.Count - 1)) break;
        var language = country.languages[x];
        //Get the letter for the column
        var columnLetter = GetColumnLetter(4 + x);
        //Set the language name
        workSheet[$"{columnLetter}{i}"].Value = language.name;
    }
}
For i = 2 To countries.Count - 1
	Dim country = countries(i)
	'Set the basic values
	workSheet($"A{i}").Value = country.name
	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 > (country.languages.Count - 1) Then
			Exit For
		End If
		Dim language = country.languages(x)
		'Get the letter for the column
		Dim columnLetter = GetColumnLetter(4 + x)
		'Set the language name
		workSheet($"{columnLetter}{i}").Value = language.name
	Next x
Next i

VB   C#


Object Reference and Resources

You may also find the IronXL class documentation within the Object Reference of great 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 variety of spreadsheet formats. It does not require Microsoft Excel to be installed, and is not dependant on Interop.


Tutorial Quick Access

Download this Tutorial as C# Source Code

The full free 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.

Use this code as an easy way to get up and running in just a few minutes. The project is saved as 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

.NET Solution Director working with Microsoft Excel document IO

Christian Findlay

Software Development Team Lead

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

All programmers need to learn how to read excel files. This is the information age, and many people store their data in excel files because they are user-friendly. Programmers must also know all about reading excel files in their respective programming language.

If you are a .Net Programmer and struggling with reading excel files, then don’t worry — you are in the right place. I will show you a step-by-step for reading excel files using C#.

You might be thinking that reading excel files would be difficult and require high-level expertise, but this is not the case. I will show you that it only takes 2-3 lines of code with IronXL to be able to read excel files.

We will be covering the following topics in this article:

  1. Introduction to IronXL
  2. Creating an Example Project for our Demonstration
  3. Adding IronXL Nuget Package to our Project

    a. Installing IronXL using the Package Manager Console
    b. Installing IronXL using the Manage Package Manager
    c. Directly download it and add a reference to the project

  4. Read the Excel file in C#

    a. Designing the Form
    b. Code to Read the data from Excel
    c. Code to Read data within a specific range
    d. Code to Read XLs and XLSX File
    e. Code to Read CSV files

  5. Summary

Introduction to IronXL:

IronXL is a .Net Library development brought to you by Iron Software. This library provides excellent functions and APIs to help us read, create and update/edit our excel files and spreadsheets. IronXL does not require Excel to be installed on your server or Interop. Moreover, IronXL provides a faster and more intuitive API than Microsoft Office Interop Excel.

IronXL works on .Net Core 2, Framework 4.5, Azure, Mono and, Mobile and Xamarin.
Image description

Creating an Example Project for our Demonstration

I will be using Windows Form App as an example, but you can use one of your choice, such as Asp.Net Web App, .Net core MVC or .Net Core web api.

To create a new project, open Visual Studio, click on «Create New Project» => Select Template; I am using the Windows Form App, you can use any of your choosing. => Click on Next Button => Name Your Project; I have named mine as «C Sharp Read Excel File». => Click on Next = > Select your Target Framework; I am selecting .Net core 3.1, but again, you can choose your own. => Finally, click on «Create Project», and a project will be created and opened for you as shown below:
Project

Our next task is to Install the Nuget Package for IronXL.

(adsbygoogle = window.adsbygoogle || []).push({});

Adding the IronXL Nuget Package

We can add the IronXL Package in one of any three ways, so you can choose the method that suits you best.

Installing IronXL using the Package Manager Console

Open the Package Manager console in your Project and use the following command:

Go to Tools => NuGet Package Manager => Package Manager Console.

Image description
This will open the Package Manager console for you. Next, write the following command in the Package Manager console:

PM > Install-Package IronXL.Excel

Image description

Installing IronXL using the Nuget Package Manager

This is another way to install the Nuget Package Manager. If you have already completed installation using the previous method, than you won’t need to use this one.

Go to: Tools = > NuGet Package Manager => Manage NuGet Packages for Solution, and click on it.

This will open the Nuget-Solution for you; click on «Browse» and search for IronXL.Excel in the search bar:
Image description
Click on the «Install» button and it will install IronXL for you. After installing IronXL, go to your form and start designing it.

Downloading IronXL

Another way of using IronXL is to download it directly from this link. Once downloaded, just add the reference of the file in your project and start using it.

Design the Form

Now, we have to design the form to suit our requirements. I will use the minimum design for the demonstration. You can use any design depending on your needs.

Go to the ToolBox=> Select Label (for name our example app), and select the «Panel and Data» grid view. Put the «Data» grid view inside the panel. Our design will look like the following:
Image description
Our form has now been designed. Our next task is to actually write the code for reading an excel file or excel sheet in C#.

Write Code for Reading Excel Files in C

We want our app to read any given excel file at the click of a button, so for this, double-click on the «Read Excel File» button, and the following code will appear:

private void button1_Click(object sender, EventArgs e)
        {
        }

Enter fullscreen mode

Exit fullscreen mode

Next, add the following namespace in this file:

using System;
using System.Windows.Forms;
using IronXL;
using System.Data;

Enter fullscreen mode

Exit fullscreen mode

Using the IronXL namespace is necessary to access the IronXL functions. However, you can use other namespaces as per the requirements of your own projects.

WorkBook workbook = WorkBook.Load("Weather.xlsx");
            WorkSheet sheet = workbook.GetWorkSheet("Sheet1");
            DataTable dt = sheet.ToDataTable(true);
            dataGridView1.DataSource = dt;

Enter fullscreen mode

Exit fullscreen mode

The first statement will load the excel workbook «Weather.xlsx» for us. I have chosen the xlsx file format as an example. You can choose any file of your choice.

After loading the excel workbook, we need to select the excel worksheet we want to read. After that, we need to convert our worksheet into a data table so that we can further load it into our Data Grid View.

This will read the file for us and display all its data in the data grid view.

Output for Reading the Data from Excel File using C#:

Image description

Let’s open our «Weather.xlsx» file in Microsoft Excel and compare our output. xlsx file is the extension for a Microsoft Excel file.

Excel File:

Read Excel
Now that we can read excel files using C#, let’s explore some advanced options.

Let’s suppose that you want to read the data from an excel file for a specific cell range. Let’s look at how to do that.

Read Data from Excel within a Specific Cell Range:

To read the data in a specific cell range, write the following code behind the button:

WorkBook workbook = WorkBook.Load("Weather.xlsx");
            WorkSheet sheet = workbook.GetWorkSheet("Sheet1");
            var range = sheet["A1:C6"];
            DataTable dt = range.ToDataTable(true);
            dataGridView1.DataSource = dt;

Enter fullscreen mode

Exit fullscreen mode

The first two lines are the same as those for loading the workbook and selecting the worksheet we want to read. On the third line, we have selected the cell range within which we want to read the data. I have selected the range A1:C6 which means that it will read the first three columns: Column A, Column B, and Column C, as well as the first six rows, as shown below.

Output for Read Data within a Specific Cell Range:

Image description

Read XLS or XLSX File:

We can read excel files no matter whether the file format is xls or xlsx. In the previous example, we looked at the example of reading the data from an Xslx file. Next, let’s look at saving the same file in .xls format and then reading it. The code will remain the same, we just have to change the file name to «Wather.xls» as shown below:

WorkBook workbook = WorkBook.Load("Weather.xls");

Output for Reading XLS File:

Image description

Read CSV File in C#:

If you have csv files instead of an excel file, you have to make slight changes to the code.
Let’s look at the following example.
I have the same Weather file saved as «Weather.csv», so I am using the same file for all the examples. Again, you can use any example according to your requirements.

WorkBook workbook = WorkBook.LoadCSV("Weather.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
            WorkSheet sheet = workbook.DefaultWorkSheet;
            DataTable dt = sheet.ToDataTable(true);
            dataGridView1.DataSource = dt;

Enter fullscreen mode

Exit fullscreen mode

On the first line will load the csv file for you and define the file format. The second line will select the worksheet, while the other two code lines are the same as those in the previous examples.

Output for Reading CSV File

Image description

Summary:

In this tutorial we have learned how to read data using excel in C# by selecting specific cells and ranges, or different file formats. This all was done with just a few lines of code.

If you want to learn more about Iron Software products, please click on this link. If you decide that you’d like to try it out for yourself, then go ahead and take advantage of the Iron Software 30-day Free-Trial . You may also want to take a look at the Iron Suite, this complete package includes five .Net Libraries, this special offer means you can get all five products for the price of only two. For more information, please click here.

I hope that you have found this guide helpful and easy to follow. If you need any further assistance, please feel free to post a comment.

Время на прочтение
7 мин

Количество просмотров 69K

В современном мире разработки приложений нередко встает необходимость работы с Excel документами. Чаще всего это разного рода отчеты, но иногда xls/x файлы используются в качестве хранилища данных. Например, если пользователь должен иметь возможность загрузить данные в приложение или выгрузить, в человеко-читаемом виде, Excel де-факто является стандартом. Относительно дружелюбный интерфейс, прозрачная структура, в купе с его распространенностью… трудно навскидку назвать решение лучше.

Однако, у многих Excel до сих пор ассоциируется с чем-то тяжелым, неповоротливым и сложным. Давайте посмотрим, как мы — обычные C# разработчики, можем легко сформировать простой Excel документ, на примере табличного отчета.

Историческая справка

Времена, когда доминировал проприетарный формат .xls(Excel Binary File Format) давно прошли и сейчас мы имеем только .xlsx(Excel Workbook), в рамках Office Open XML. Последний представляет собой обычный .zip архив с XML файлами. Не будем углубляться в его структуру, я искренне надеюсь что вам это никогда не понадобится.

На github, и не только, можно найти ряд библиотек, бесплатных и не только. Пожалуй самой популярной является EPPlus. До определенной степени, она довольно хорошо отражает концепцию Excel, именно по этому я всегда использую EPPlus. Версия 4 полностью бесплатна, начиная с 5‐й версии вам потребуется приобрести лицензию для коммерческого использования.

Задача

Итак, предположим, продукт-мэнеджеру ударила в голову идея того, что возможность выгружать некий отчет в формате Excel увеличит кол-во пользователей на 100500%. Проджет-менеджер решает выкатить эту киллер-фичу как хотфикс прямо сегодня — ведь работы всего на пару часов.

Сам по себе, отчет содержит краткое описание компании и историю изменения некоторых экономических показателей. Для простоты все свойства компании — строки. Экономические показатели — большие целые числа и числа с плавающей точкой, а также даты. Предположим, что где-то в недрах микросервисного backend-да есть сервис-генератор подобных отчетов, например по id компании. Однако, поскольку id нет смысла выводить пользователю, идентификатор отсутствует в самой модели отчета.

Аналитик, в свою очередь, выдает задачу с феноменально точным описанием — «Сгенерировать excel отчет на базе данных MarketReport». Что ж, для нашего примера, создадим заглушку — генератор фейковых данных:

Первый запуск

Подключим EPPlus версии 4.5.3.3 и создадим базовую обвязку для будущего генератора.

Сердцем генератора будет метод Generate. ExcelPackage это модель документа, через которую мы и будем осуществлять все взаимодействия с ним. Также имеется конструктор для передачи пути к файлу или потока.

В методе main создается генератор отчетов, а также генератор Excel файлов. Далее полученный файл просто записывается на диск.

При попытке запустить приложение, получаем exception:InvalidOperationException: The workbook must contain at least one worksheet

Все правильно, Excel документ не может существовать без страниц, должна быть хотя бы одна. Добавляем ее, все интуитивно понятно:

var sheet = package.Workbook.Worksheets    
		.Add("Market Report");

Запускаем снова и… вот оно! Теперь наше приложение генерирует документ и, хотя там еще ничего нет, он уже весит 2,5KB — значит мы работаем с Excel правильно и все идет как надо.

Вывод данных

Давайте выведем основную информацию по компании в шапку. Для доступа к конкретной ячейки объект Cells на странице пакета снабжен удобным индексатором. При этом, до конкретной ячейки можно достучаться как через номер строки и столбца, так и по привычному всем буквенно-числовому коду:

sheet.Cells["B2"].Value = "Company:";
sheet.Cells[2, 3].Value = report.Company.Name;

Полный код вывода шапки.

sheet.Cells["B2"].Value = "Company:";
sheet.Cells[2, 3].Value = report.Company.Name;
sheet.Cells["B3"].Value = "Location:";
sheet.Cells["C3"].Value = $"{report.Company.Address}, " +
  												$"{report.Company.City}, " +                          
  												$"{report.Company.Country}";
sheet.Cells["B4"].Value = "Sector:";
sheet.Cells["C4"].Value = report.Company.Sector;
sheet.Cells["B5"].Value = report.Company.Description;

Для вывода исторических данных понадобится как минимум шапка таблицы и цикл по массиву History:

sheet.Cells[8, 2, 8, 4].LoadFromArrays(new object[][]{ new []{"Capitalization", "SharePrice", "Date"} });
var row = 9;
var column = 2;
foreach (var item in report.History)
{
  sheet.Cells[row, column].Value = item.Capitalization;
  sheet.Cells[row, column + 1].Value = item.SharePrice;
  sheet.Cells[row, column + 2].Value = item.Date;    
  row++;
}

Предлагаю обратить внимание на метод LoadFromArrays, который заполняет диапазон ячеек рваным(зубчатым) массивом. Здесь мы можем видеть, что типизация теряется и передавая массив object мы ожидаем что EPPlus в конечном итоге использует ToString, чтобы записать переданное в ячейки.

Стилизация

Если вы прямо сейчас откроете документ, то вы возможно увидите не то, что хотелось бы отдать в продакшн в пятницу вечером.

Как это выглядит

Во-первых, шапка никак не выделяется, во-вторых таблица не имеет границ… выравнивание пляшет, даты отображаются магическими числами, а капитализация «уходит в какую-то математику» — как это прокомментировал аналитик.

Да, на все эти красивости у нас уйдет больше года кода, чем на сам вывод данных, и, в конечном тоге, получившаяся каша из логики вывода данных и разметки заставит некоторых усомниться в их компетентности… но, мы же backend разработчики, так давайте сверстаем Excel Sheet!

Размер ячеек

Из коробки у нас есть возможность сделать автофит а так же вручную выставить ширину в соответствии с нашей ситуацией. А ситуация у нас не самая хорошая — по задумке аналитика в шапке у ячеек должен быть автофит, а у ячеек таблицы — тоже автофит. Так в чем же подвох?

Если вы когда-нибудь до этого открывали Excel, то возможно знаете, что ширина ячеек не может отличаться в рамках столбца и автофит будет по самому широкому контенту ячейки. Однако, простые вещи бывает нетак то просто объяснить… Но если вы справитесь, то вот как это будет выглядеть в коде:

sheet.Cells[1, 1, row, column + 2].AutoFitColumns();
sheet.Column(2).Width = 14;
sheet.Column(3).Width = 12;

Формат данных

Как и большая часть стиля ячейки, он задается через одноименное свойство Style. Обратите внимание на вычисление 3-го аргумента индексатора. Это звоночек некачественного кода, но к этому мы вернемся в позже…

sheet.Cells[9, 4, 9 + report.History.Length, 4].Style.Numberformat.Format = "yyyy";
sheet.Cells[9, 2, 9 + report.History.Length, 2].Style.Numberformat.Format =  "### ### ### ##0";

Выравнивание

Его можно задать как на ячейке, так и на диапазоне. На самом деле, для EPPlus, это одна и та же сущность — некий ExcelRange, описывающий диапазон ячеек, в том числе и со всего 1 ячейкой.

sheet.Column(2).Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
sheet.Cells[8, 3, 8 + report.History.Length, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

Стиль текста

Также легко задается, используя Style.Font, кстати, здесь, на 2-й строчке, мы впервые указываем диапазон так, как привыкли его видеть пользователи Excel:

sheet.Cells[8, 2, 8, 4].Style.Font.Bold = true;
sheet.Cells["B2:C4"].Style.Font.Bold = true;

Границы

Задаем стиль линии, а также ее толщину. К этому моменту от кол-ва магических чисел-параметров индексатора уже рябит в глазах, но мы уже на финишной прямой… не так ли?

sheet.Cells[8, 2, 8 + report.History.Length, 4].Style.Border.BorderAround(ExcelBorderStyle.Double);
sheet.Cells[8, 2, 8, 4].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;

График

«Ну что за отчет без графиков, верно, Карл?» — ловко подметит специалист по тестированию, и не важно, что этого не было в ТЗ а на часах уже половина 9-го…

Хотя график как сущность сам по себе сложнее таблиц и с графиками мы не работаем каждый день, EPPlus предоставляет довольно понятный API. Давайте добавим простейший график, отражающий рост капитализации:

var capitalizationChart = sheet.Drawings.AddChart("FindingsChart", OfficeOpenXml.Drawing.Chart.eChartType.Line);
capitalizationChart.Title.Text = "Capitalization";
capitalizationChart.SetPosition(7, 0, 5, 0);
capitalizationChart.SetSize(800, 400);
var capitalizationData = (ExcelChartSerie)(capitalizationChart.Series.Add(sheet.Cells["B9:B28"], sheet.Cells["D9:D28"]));
capitalizationData.Header = report.Company.Currency;

Еще, может понадобиться защитить страницу от редактирования:

sheet.Protection.IsProtected = true;

На этом все, репозиторий с рабочим приложением находится здесь.

Заключение

О чем говорит финальная версия метода Generate?

public byte[] Generate(MarketReport report)
{    
  var package = new ExcelPackage();    
  
  var sheet = package.Workbook.Worksheets        
    	.Add("Market Report");      
  
  sheet.Cells["B2"].Value = "Company:";    
  sheet.Cells[2, 3].Value = report.Company.Name;    
  sheet.Cells["B3"].Value = "Location:";    
  sheet.Cells["C3"].Value = $"{report.Company.Address}, " +
    												$"{report.Company.City}, " +                             
    												$"{report.Company.Country}";    
  sheet.Cells["B4"].Value = "Sector:";    
  sheet.Cells["C4"].Value = report.Company.Sector;    
  sheet.Cells["B5"].Value = report.Company.Description;    
  
  sheet.Cells[8, 2, 8, 4].LoadFromArrays(new object[][]{ new []{"Capitalization", "SharePrice", "Date"} });    
  var row = 9;    
  var column = 2;    
  foreach (var item in report.History)    
  {        
    	sheet.Cells[row, column].Value = item.Capitalization;        
   		sheet.Cells[row, column + 1].Value = item.SharePrice;        
   		sheet.Cells[row, column + 2].Value = item.Date;        
    	row++;    
  }    
  
  sheet.Cells[1, 1, row, column + 2].AutoFitColumns();    
  sheet.Column(2).Width = 14;    
  sheet.Column(3).Width = 12;        
  
  sheet.Cells[9, 4, 9+ report.History.Length, 4].Style.Numberformat.Format = "yyyy";    
  sheet.Cells[9, 2, 9+ report.History.Length, 2].Style.Numberformat.Format =  "### ### ### ##0";    
  
  sheet.Column(2).Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;    
  sheet.Cells[8, 3, 8 + report.History.Length, 3].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;    
  sheet.Column(4).Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;    
  
  sheet.Cells[8, 2, 8, 4].Style.Font.Bold = true;    
  sheet.Cells["B2:C4"].Style.Font.Bold = true;
  
  sheet.Cells[8, 2, 8 + report.History.Length, 4].Style.Border.BorderAround(ExcelBorderStyle.Double);    
  sheet.Cells[8, 2, 8, 4].Style.Border.Bottom.Style = ExcelBorderStyle.Thin;     
  
  var capitalizationChart = sheet.Drawings.AddChart("FindingsChart", OfficeOpenXml.Drawing.Chart.eChartType.Line);    
  capitalizationChart.Title.Text = "Capitalization";    
  capitalizationChart.SetPosition(7, 0, 5, 0);    
  capitalizationChart.SetSize(800, 400);    
  var capitalizationData = (ExcelChartSerie)(capitalizationChart.Series.Add(sheet.Cells["B9:B28"], sheet.Cells["D9:D28"]));    
  capitalizationData.Header = report.Company.Currency;       
  
  sheet.Protection.IsProtected = true;    
  
  return package.GetAsByteArray();
}

Во-первых, прежде всего, о том, что мы успешно справились с задачей, а именно, сгенерировали свой первый Excel отчет, поработали со стилями и даже решили пару попутных проблем.

Во-вторых, возможно имеет смысл искать новою работу, но, забегая вперед, я бы с этим не спешил… Если данная публикация наберет 1+ просмотров, то во второй части мы поговорим о том, как можно отделить стилизацию от логики заполнения данными, упростить манипуляции над ячейками и в целом сделаем код боле поддерживаемым.

Read write excel in dotnet core 21 epplus

Today in this article, we shall see how to perform Read and Write Excel files in .NET Core-based application.

You must be wondering if there is an easy way to work on Excel in the .NET Core framework.

Here I am going to talk about a very simple approach of using OpenXML SDK from Microsoft (which is free and open-source).

The OpenXML SDK provides API for working with Office Word, Excel, and PowerPoint documents.

This SDK can be installed from NuGet as a package.

Today, in this article we shall cover below,

  • You don’t need Microsoft Office
  • Read the content of the excel file using OpenXML API
  • Read Excel as JSON
  • Read Excel with Empty cell values
  • Export/Create/Write data to Excel using OpenXML
  • Summary

You don’t need Microsoft Office

Please note that Read, and Create Excel(.xls, .xlsx) in C# is possible without installing Microsoft Office.

Yes, you don’t really need Microsoft Office to be installed on the machine.

Today we will see a few possible and easy-to-implement approaches.

If you are interested in a few more approaches like using EPPlus or NPOI library, kindly visit the below post for more details,

  • Read/Write Excel files in .NET Core using EPPlus
  • Read/Write Excel files in .NET Core using NPOI

Getting Started

Let’s create a .NET Core project, you can choose any project template, and this SDK works perfectly for all projects. Here to keep it simple I am using a Console .NET Core 3.1 C# application.

(Below logic works perfectly fine for older .NET Core 2.x or any new .NET 5 or 6 version)

image 5

The NuGet package name is DocumentFormat.OpenXml. Let’s install this package,

PM> Install-Package Open-XML-SDK -Version 2.9.0 

Note: Please use the latest available version.

OR

Please install it from the Nuget package manager,

Read write excel in dotnet core

Once you install this NuGet package, you get full library support on Reading, Writing Excel (.xlsx), Word (.doc), or Powerpoint(.ppt) files using C# API.

Let’s look at an example, I have a simple Excel file with the below column and row details. Let’s try to read the file using our API,

export import excel C

Read the content of the excel file using OpenXML API

POC example as below. This ready to use API can be used in .NET Core console, or Test project or ASP.NET Core application or logic can be modified or improved as per your requirements.

Sample methods are as below,

  static void ReadExcelFile()
        {
            try
            {
                //Lets open the existing excel file and read through its content . Open the excel using openxml sdk
                using (SpreadsheetDocument doc = SpreadsheetDocument.Open("testdata.xlsx", false))
                {
                    //create the object for workbook part  
                    WorkbookPart workbookPart = doc.WorkbookPart;
                    Sheets thesheetcollection = workbookPart.Workbook.GetFirstChild<Sheets>();
                    StringBuilder excelResult = new StringBuilder();

                    //using for each loop to get the sheet from the sheetcollection  
                    foreach (Sheet thesheet in thesheetcollection)
                    {
                        excelResult.AppendLine("Excel Sheet Name : " + thesheet.Name);
                        excelResult.AppendLine("----------------------------------------------- ");
                        //statement to get the worksheet object by using the sheet id  
                        Worksheet theWorksheet = ((WorksheetPart)workbookPart.GetPartById(thesheet.Id)).Worksheet;

                        SheetData thesheetdata = (SheetData)theWorksheet.GetFirstChild<SheetData>();
                        foreach (Row thecurrentrow in thesheetdata)
                        {
                            foreach (Cell thecurrentcell in thecurrentrow)
                            {
                                //statement to take the integer value  
                                string currentcellvalue = string.Empty;
                                if (thecurrentcell.DataType != null)
                                {
                                    if (thecurrentcell.DataType == CellValues.SharedString)
                                    {
                                        int id;
                                        if (Int32.TryParse(thecurrentcell.InnerText, out id))
                                        {
                                            SharedStringItem item = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(id);
                                            if (item.Text != null)
                                            {
                                                //code to take the string value  
                                                excelResult.Append(item.Text.Text + " ");
                                            }
                                            else if (item.InnerText != null)
                                            {
                                                currentcellvalue = item.InnerText;
                                            }
                                            else if (item.InnerXml != null)
                                            {
                                                currentcellvalue = item.InnerXml;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    excelResult.Append(Convert.ToInt16(thecurrentcell.InnerText) + " ");
                                }
                            }
                            excelResult.AppendLine();
                        }
                        excelResult.Append("");
                        Console.WriteLine(excelResult.ToString());
                        Console.ReadLine();
                    }
                }
            }
            catch (Exception)
            {

            }
        }

After executing the above logic, one can easily read all the Excel details.

  • In the above example, I have used the file “testdata.xlsx” as input. I have kept this file in the output directory binDebug
  • Also if needed you can keep the file locally for ex.
    string strDoc = @”C:UsersPublicDocumentstestdata.xlsx” then use the method as below,
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(strDoc, false))

I am showing the results on a console,

Read excel in dotnet core

One can map the above output details to respective C# class objects using the mapping logic of their choice.

This way data can be transferred for further processing within the application if needed. For example for write operations, I have used a similar C# class UserDetails.

Read Excel as JSON

If you are interested to convert Excel as JSON it’s easy too. Please see here to know more about the same.

  • Read Excel as JSON using OpenXML SDK

Read Excel with Empty cell values

If you are interested to export Excel in C# with empty cell values, please see here one approach to reading excel data appropriately.

  • Read Excel with Empty cell values using OpenXML SDK

Export/Create/Write data to Excel using OpenXML

Let’s try now try to create or write the data to an Excel file.

Here is the sample data/object which we want to save as an Excel file.

Create excel xlsx C NET 5

Create excel xlsx C

Here we need to use the OpenXML Create () C# method as shown below,

I am creating a new Excel file in the same project folder to keep everything simple. (Excel file will get created in the ‘bin‘ folder of the project)

The complete logic can be found below,

 static void WriteExcelFile()
        {
            List<UserDetails> persons = new List<UserDetails>()
            {
                new UserDetails() {ID="1001", Name="ABCD", City ="City1", Country="USA"},
                new UserDetails() {ID="1002", Name="PQRS", City ="City2", Country="INDIA"},
                new UserDetails() {ID="1003", Name="XYZZ", City ="City3", Country="CHINA"},
                new UserDetails() {ID="1004", Name="LMNO", City ="City4", Country="UK"},
           };

            // Lets converts our object data to Datatable for a simplified logic.
            // Datatable is most easy way to deal with complex datatypes for easy reading and formatting. 
            DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(persons), (typeof(DataTable)));

            using (SpreadsheetDocument document = SpreadsheetDocument.Create("TestNewData.xlsx", SpreadsheetDocumentType.Workbook))
            {
                WorkbookPart workbookPart = document.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();

                WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                var sheetData = new SheetData();
                worksheetPart.Worksheet = new Worksheet(sheetData);

                Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
                Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };

                sheets.Append(sheet);

                Row headerRow = new Row();

                List<String> columns = new List<string>();
                foreach (System.Data.DataColumn column in table.Columns)
                {
                    columns.Add(column.ColumnName);

                    Cell cell = new Cell();
                    cell.DataType = CellValues.String;
                    cell.CellValue = new CellValue(column.ColumnName);
                    headerRow.AppendChild(cell);
                }

                sheetData.AppendChild(headerRow);

                foreach (DataRow dsrow in table.Rows)
                {
                    Row newRow = new Row();
                    foreach (String col in columns)
                    {
                        Cell cell = new Cell();
                        cell.DataType = CellValues.String;
                        cell.CellValue = new CellValue(dsrow[col].ToString());
                        newRow.AppendChild(cell);
                    }

                    sheetData.AppendChild(newRow);
                }

                workbookPart.Workbook.Save();
            }
        }

Once you execute this API ‘workbookPart.Workbook.Save()’ will save the file to the ‘bin’ folder location. You can modify the location of the generated file if needed.

After executing the above API, a new Excel file will be created with the above custom objects transformed into respective Excel Columns and Rows details as below,

Write to excel in NET Core

That’s all, we just learned how to import and export data to/from excel in a simple way in .NET Core framework-based application.

Please visit the GitHub link for the complete code.

Other References :

EPPlus and EPOI for Reading and Writing of Excel file, kindly visit the below post for more details.

  • Read/Write Excel file in .NET Core using EPPlus
  • Read/Write Excel file in .NET Core using NPOI

If interested to know on how to download excel(.xlsx) file, please see the below article,

  •  Return or Download File in ASP.NET Core WebAPI

Please use the below Tutorial to use the above code and quickly get started,

This was very much basic while dealing with Excel in .NET Core which we covered today in this article.

Hope this helps you get started.

Are you dealing with any complex scenarios? Please let me know and sound off your comments below!

Summary

The Open XML SDK provides us full control to deal with Office Word, Excel, and PowerPoint documents. As this SDK is free and open-source from Microsoft, we don’t really need to use any other third-party tools/libraries. This SDK works best!


Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published best practices and guidelines for software design and development.



Introduction

It is possible that we need to read Excel files when developing. In this article, I will show one method to read Excel file contents with .NET.

As is known, there are three types of Excel file.

  1. .xls format Office 2003 and the older version
  2. .xlsx format Office 2007 and the last version
  3. .csv format String text by separating with comma (the above two format can be saved as this format.)

We need to use different ways to read the first, second format files and the third format files.

Using the Code

Foreground

  1. <div>  
  2.        <%— file upload control, using to upload the file which will be read and get file information—%>  
  3.        <asp:FileUpload ID=«fileSelect» runat=«server» />    
  4.        <%— click this button to run read method—%>  
  5.        <asp:Button ID=«btnRead» runat=«server» Text=«ReadStart» />  
  6. </div> 

Background

  1.   
  2. string currFilePath = string.Empty;   
  3. string currFileExtension = string.Empty;   
  4.   
  5.   
  6. protected void Page_Load(object sender, EventArgs e) {  
  7.   this.btnRead.Click += new EventHandler(btnRead_Click);  
  8. }  
  9.   
  10.   
  11. protected void btnRead_Click(object sender, EventArgs e) {  
  12.   Upload();   
  13.   if (this.currFileExtension == «.xlsx» || this.currFileExtension == «.xls») {  
  14.     DataTable dt = ReadExcelToTable(currFilePath);   
  15.   } else if (this.currFileExtension == «.csv») {  
  16.     DataTable dt = ReadExcelWidthStream(currFilePath);   
  17.   }  

The following shows three
methods in button click event.

  1.   
  2.   
  3.   
  4. private void Upload() {  
  5.   HttpPostedFile file = this.fileSelect.PostedFile;  
  6.   string fileName = file.FileName;  
  7.   string tempPath = System.IO.Path.GetTempPath();   
  8.   fileName = System.IO.Path.GetFileName(fileName);   
  9.   this.currFileExtension = System.IO.Path.GetExtension(fileName);   
  10.   this.currFilePath = tempPath + fileName;   
  11.   file.SaveAs(this.currFilePath);   
  12. }  
  13.   
  14.   
  15.   
  16.   
  17.   
  18.   
  19. private DataTable ReadExcelToTable(string path) {  
  20.     
  21.   string connstring = «Provider=Microsoft.ACE.OLEDB.12.0;Data Source=» + path + «;Extended Properties=’Excel 8.0;HDR=NO;IMEX=1′;»  
  22.   string connstring = Provider = Microsoft.JET.OLEDB .4 .0;  
  23.   Data Source = » + path + «;  
  24.   Extended Properties = » ‘Excel 8.0;HDR=NO;IMEX=1’;»  
  25.   using(OleDbConnection conn = new OleDbConnection(connstring)) {  
  26.     conn.Open();  
  27.     DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { nullnullnull«Table» });   
  28.     string firstSheetName = sheetsName.Rows[0][2].ToString();   
  29.     string sql = string.Format(«SELECT * FROM [{0}],firstSheetName»);   
  30.     OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);  
  31.     DataSet set = new DataSet();  
  32.     ada.Fill(set);  
  33.     return set.Tables[0];  
  34.   }  
  35. }  
  36.   
  37.   
  38.   
  39.   
  40.   
  41. private DataTable ReadExcelWithStream(string path) {  
  42.   DataTable dt = new DataTable();  
  43.   bool isDtHasColumn = false  
  44.   StreamReader reader = new StreamReader(path, System.Text.Encoding.Default);   
  45.   while (!reader.EndOfStream) {  
  46.     string meaage = reader.ReadLine();  
  47.     string[] splitResult = message.Split(new char[] { ‘,’ }, StringSplitOption.None);   
  48.     DataRow row = dt.NewRow();  
  49.     for (int i = 0; i < splitResult.Length; i++) {  
  50.       if (!isDtHasColumn)   
  51.       {  
  52.         dt.Columns.Add(«column» + i, typeof(string));  
  53.       }  
  54.       row[i] = splitResult[i];  
  55.     }  
  56.     dt.Rows.Add(row);   
  57.     isDtHasColumn = true  
  58.   }  
  59.   return dt;  

Conclusion

This article is just used for reference and studying easily. Therefore, there are not complicated situations considered in this method.

In addition, I want to recommand two articles about operating Excel for you.

http://www.codeproject.com/KB/aspnet/coolcode2_aspx.aspx

http://www.codeproject.com/KB/cs/csharpexcel.aspx

Понравилась статья? Поделить с друзьями:
  • Read excel file into
  • Read excel file in к xlsx
  • Read excel file in python pandas
  • Read excel file from javascript
  • Read excel data in python