С read excel spreadsheet

I am using Microsoft.Office.Interop.Excel to read a spreadsheet that is open in memory.

gXlWs = (Microsoft.Office.Interop.Excel.Worksheet)gXlApp.ActiveWorkbook.ActiveSheet;
int NumCols = 7;
string[] Fields = new string[NumCols];
string input = null;
int NumRow = 2;
while (Convert.ToString(((Microsoft.Office.Interop.Excel.Range)gXlWs.Cells[NumRow, 1]).Value2) != null)
{
    for (int c = 1; c <= NumCols; c++)
    {
        Fields[c-1] = Convert.ToString(((Microsoft.Office.Interop.Excel.Range)gXlWs.Cells[NumRow, c]).Value2);
    }
    NumRow++;

    //Do my other processing
}

I have 180,000 rows and this turns out be very slow. I am not sure the «Convert» is efficient. Is there anyway I could do this faster?

Moon

asked Sep 30, 2011 at 17:27

ManInMoon's user avatar

2

Hi I found a very much faster way.

It is better to read the entire data in one go using «get_range». This loads the data into memory and I can loop through that like a normal array.

Microsoft.Office.Interop.Excel.Range range = gXlWs.get_Range("A1", "F188000");
object[,] values = (object[,])range.Value2;
int NumRow=1;
while (NumRow < values.GetLength(0))
{
    for (int c = 1; c <= NumCols; c++)
    {
        Fields[c - 1] = Convert.ToString(values[NumRow, c]);
    }
    NumRow++;
}

answered Oct 1, 2011 at 5:37

ManInMoon's user avatar

ManInMoonManInMoon

6,70515 gold badges68 silver badges132 bronze badges

7

There are several options — all involve some additional library:

  • OpenXML 2.0 (free library from MS) can be used to read/modify the content of an .xlsx so you can do with it what you want

  • some (commercial) 3rd-party libraries come with grid controls allowing you to do much more with excel files in your application (be it Winforms/WPF/ASP.NET…) like SpreadsheetGear, Aspose.Cells etc.

answered Sep 30, 2011 at 17:34

Yahia's user avatar

YahiaYahia

69.2k9 gold badges113 silver badges144 bronze badges

4

I am not sure the «Convert» is efficient. Is there anyway I could do
this faster?

What makes you believe this? I promise you that Convert.ToString() is the most effective method in the code you posted. Your problem is that your looping through 180,000 records in an excel document…

You could split the work up since you know the number of row this is trival to do.

Why are you coverting Value2 to a string exactly?

answered Sep 30, 2011 at 17:41

Security Hound's user avatar

Security HoundSecurity Hound

2,5143 gold badges24 silver badges42 bronze badges

2

I found really fast way to read excel in my specific way. I need to get it as a two dimensional array of string. With really big excel, it took about one hour in old way. In this way, I get my values in 20sec.

I am using this nugget: https://reposhub.com/dotnet/office/ExcelDataReader-ExcelDataReader.html

And here is my code:

DataSet result = null;
//https://reposhub.com/dotnet/office/ExcelDataReader-ExcelDataReader.html
using (var stream = File.Open(path, FileMode.Open, FileAccess.Read))
{
    // Auto-detect format, supports:
    //  - Binary Excel files (2.0-2003 format; *.xls)
    //  - OpenXml Excel files (2007 format; *.xlsx)
    using (var reader = ExcelReaderFactory.CreateReader(stream))
    {
        result = reader.AsDataSet();
    }
}

foreach (DataTable table in result.Tables)
{
    if (//my conditions)
    {
        continue;
    }

    var rows = table.AsEnumerable().ToArray();

    var dataTable = new string[table.Rows.Count][];//[table.Rows[0].ItemArray.Length];
    Parallel.For(0, rows.Length, new ParallelOptions { MaxDegreeOfParallelism = 8 },
        i =>
        {
            var row = rows[i];
            dataTable[i] = row.ItemArray.Select(x => x.ToString()).ToArray();                                    
        });

    importedList.Add(dataTable);
}

camille's user avatar

camille

16.2k18 gold badges38 silver badges60 bronze badges

answered Sep 13, 2021 at 10:55

Míra Kníra Němec's user avatar

I guess it’s not the Convert the source of «slowing»…

Actually, retrieving cell values is very slow.

I think this conversion is not necessary:

(Microsoft.Office.Interop.Excel.Range)gXlWs

It should work without that.

And you can ask directly:

gXlWs.Cells[NumRow, 1].Value != null

Try to move the entire range or, at least, the entire row to an object Matrix and work with it instead of the range itself.

answered Sep 30, 2011 at 17:40

masaishi's user avatar

5

Use the OleDB Method. That is the fastest as follows;

string con =
  @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:temptest.xls;" + 
  @"Extended Properties='Excel 8.0;HDR=Yes;'";    
using(OleDbConnection connection = new OleDbConnection(con))
{
    connection.Open();
    OleDbCommand command = new OleDbCommand("select * from [Sheet1$]", connection); 
    using(OleDbDataReader dr = command.ExecuteReader())
    {
         while(dr.Read())
         {
             var row1Col0 = dr[0];
             Console.WriteLine(row1Col0);
         }
    }
}

Zeeshan Ahmad Khalil's user avatar

answered Jun 14, 2019 at 16:44

Manvir Randhawa's user avatar

Opening Excel files in code has been a painful experience long before .NET Core came along. In many cases, you actually needed the Excel application installed on the target/users machine to be able to open excel files via code. If you’ve ever had to use those “OLE DB Jet ” queries before, you know it’s not a great experience. Luckily there are some pretty good open source solutions now that don’t require excel on the target machine. This is good for Windows users so that you don’t have to install excel on a target users machine or web server, but also for people hosting .NET Core applications on Linux (And even Mac/ARM) – where Excel is obviously no where to be seen!

My methodology for this article is pretty simple. Create a standardized excel workbook with a couple of sheets, couple of formulas, and a couple of special formatting cases. Read the same data out in every single library and see which one works the best for me. Simple! Let’s get going!

Create Spreadsheet Magic with IronXL – Read, Write and Create in C# .NET

Having helped Lego and NASA with their spreadsheet woes – IronXL provides for your spreadsheet needs by validating, converting, saving, and modifying Excel files. IronXL reads, writes, and creates workbook excel files in C# .NET Core in just a few lines of code. IronXL works with many excel formats such as XLS/XLSX/CSV/TSV. Test and share your project straightaway with IronXL 30-day free trial key or experience licensing benefits starting from $399 with 24-hour engineer support.

Note On CSV Formats

I should note that if you are reading a CSV, or more so a single excel sheet that doesn’t have formulas or anything “excel” specific on the sheet, you should instead just parse it using standard CSV technique. We have a great article here on parsing CSV in C# .NET that you should instead follow. CSV parsers are great for taking tabular data and deserializing it into objects and should be used where they can.

Example Data

I figure the best way to compare the different libraries on offer is to create a simple spreadsheet to compare the different ways we can read data out. The spreadsheet will have two “sheets”, where the second sheet references the first.

Sheet 1 is named “First Sheet” and looks like so :

Notice that cell A2 is simply the number “1”. Then in column B2, we have a reference to cell A2. This is because we want to check if the libraries allow us to not only get the “formula” from the cell, but also what the computed value should be.

We are also styling cell A2 with a font color of red, and B2 has a full border (Although hard to see as I’m trying to show the fomula). We will try and extract these styling elements out later.

Sheet 2 is named “Second Sheet” and looks like so :

So we are doing a simple “SUM” formula and referencing the first sheet. Again, this is so we can test getting both the formula and the computed value, but this time across different sheets. It’s not complicated for a person used to working with Excel, but let’s see how a few libraries handle it.

In general, in my tests I’m looking for my output to always follow the same format of :

Sheet 1 Data
Cell A2 Value   : 
Cell A2 Color   :
Cell B2 Formula :
Cell B2 Value   :
Cell B2 Border  :

Sheet 2 Data
Cell A2 Formula :
Cell A2 Value   :

That way when I show the code, you can pick the library that makes the most sense to you.

EPPlus

When I first started hunting around for parsing excel in .NET Core, I remembered using EPPlus many moons ago for some very lightweight excel parsing. The nuget package can be found here : https://www.nuget.org/packages/EPPlus/. It’s also open source so you can read through the source code if that’s your thing here : https://github.com/JanKallman/EPPlus

The code to read our excel spreadsheet looks like so :

static void Main(string[] args)
{
    using(var package = new ExcelPackage(new FileInfo("Book.xlsx")))
    {
        var firstSheet = package.Workbook.Worksheets["First Sheet"];
        Console.WriteLine("Sheet 1 Data");
        Console.WriteLine($"Cell A2 Value   : {firstSheet.Cells["A2"].Text}");
        Console.WriteLine($"Cell A2 Color   : {firstSheet.Cells["A2"].Style.Font.Color.LookupColor()}");
        Console.WriteLine($"Cell B2 Formula : {firstSheet.Cells["B2"].Formula}");
        Console.WriteLine($"Cell B2 Value   : {firstSheet.Cells["B2"].Text}");
        Console.WriteLine($"Cell B2 Border  : {firstSheet.Cells["B2"].Style.Border.Top.Style}");
        Console.WriteLine("");

        var secondSheet = package.Workbook.Worksheets["Second Sheet"];
        Console.WriteLine($"Sheet 2 Data");
        Console.WriteLine($"Cell A2 Formula : {secondSheet.Cells["A2"].Formula}");
        Console.WriteLine($"Cell A2 Value   : {secondSheet.Cells["A2"].Text}");
    }
}

Honestly what can I say. This was *super* easy and worked right out of the box. It picks up formulas vs text perfectly! The styles on our first sheet was also pretty easy to get going. The border is slightly annoying because you have to check the “Style” of the border, and if it’s a style of “None”, then it means there is no border (As opposed to a boolean for “HasBorder” or similar). But I think I’m just nit picking, EPPlus just works!

NPOI

NPOI is another open source option with a Github here : https://github.com/tonyqus/npoi and Nuget here : https://www.nuget.org/packages/NPOI/. It hasn’t had a release in over a year which isn’t that bad because it’s not like Excel itself has tonnes of updates throughout the year, but the Issues list on Github is growing a bit with a fair few bugs so keep that in mind.

The code to read our data using NPOI looks like so :

…..

…Actually you know what. I blew a bunch of time on this to try and work out the best way to use NPOI and the documentation is awful. The wiki is here : https://github.com/tonyqus/npoi/wiki/Getting-Started-with-NPOI but it has a few samples but most/all of them are about creating excel workbooks not reading them. I saw they had a link to a tutorial on how to read an Excel file which looked promising, but it was literally reading the spreadsheet and then dumping the text out.

After using EPPlus, I just didn’t see any reason to continue with this one. Almost every google answer will lead you to StackOverflow with people using NPOI with such specific use cases that it never really all pieced together for me.

ExcelDataReader

ExcelDataReader appeared in a couple of stackoverflow answers on reading excel in .NET Core. Similar to others in this list, it’s open source here : https://github.com/ExcelDataReader/ExcelDataReader and on Nuget here : https://www.nuget.org/packages/ExcelDataReader/

I wanted to make this work but…. It just doesn’t seem intuitive at all. ExcelDataReader works on the premise that you are reading “rows” and “columns” sequentially in almost a CSV fashion. That sort of works but if you are looking for a particular cell, it’s rough as hell.

Some example code :

static void Main(string[] args)
{
    System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
    using (var stream = File.Open("Book.xlsx", FileMode.Open, FileAccess.Read))
    {
        using (var reader = ExcelReaderFactory.CreateReader(stream))
        {
            do
            {
                while (reader.Read()) //Each ROW
                {
                    for (int column = 0; column < reader.FieldCount; column++)
                    {
                        //Console.WriteLine(reader.GetString(column));//Will blow up if the value is decimal etc. 
                        Console.WriteLine(reader.GetValue(column));//Get Value returns object
                    }
                }
            } while (reader.NextResult()); //Move to NEXT SHEET

        }
    }
}

The first line in particular is really annoying (Everything blows up without it). But you’ll notice that we are moving through row by row (And sheet by sheet) trying to get values. Ontop of that, calling things like “GetString” doesn’t work if the value is a decimal (Implicit casts would have been better IMO). I also couldn’t find any way to get the actual formula of the cell. The above only returns the computed results.

I was going to slog my way through and actually get the result we were looking for, but it’s just not a library I would use.

Syncfusion

Syncfusion is one of those annoying companies that create pay-to-use libraries, upload them to nuget, and then in small print  say you need to purchase a license or else. Personally, I would like to see Microsoft not allow paid libraries into the public Nuget repo. I’m going to include them here but their licensing starts at $995 per year, per developer, so I don’t see much reason to use it for the majority of use cases. The nuget page can be found here https://www.nuget.org/packages/Syncfusion.XlsIO.Net.Core/

The code looks like :

static void Main(string[] args)
{
    ExcelEngine excelEngine = new ExcelEngine();
    using (var stream = File.Open("Book.xlsx", FileMode.Open, FileAccess.Read))
    {
        var workbook = excelEngine.Excel.Workbooks.Open(stream);

        var firstSheet = workbook.Worksheets["First Sheet"];
        Console.WriteLine("Sheet 1 Data");
        Console.WriteLine($"Cell A2 Value   : {firstSheet.Range["A2"].DisplayText}");
        Console.WriteLine($"Cell A2 Color   : {firstSheet.Range["A2"].CellStyle.Font.RGBColor.Name}");
        Console.WriteLine($"Cell B2 Formula : {firstSheet.Range["B2"].Formula}");
        Console.WriteLine($"Cell B2 Value   : {firstSheet.Range["B2"].DisplayText}");
        Console.WriteLine($"Cell B2 Border  : {firstSheet.Range["B2"].CellStyle.Borders.Value}");
        Console.WriteLine("");

        var secondSheet = workbook.Worksheets["Second Sheet"];
        Console.WriteLine($"Sheet 2 Data");
        Console.WriteLine($"Cell A2 Formula : {secondSheet.Range["A2"].Formula}");
        Console.WriteLine($"Cell A2 Value   : {secondSheet.Range["A2"].DisplayText}");
    }
}

So not bad. I have to admit, I fiddled around trying to understand how it worked out borders (As the above code doesn’t work), but gave up. The font color also took some fiddling where the library returns non standard objects as the color. Some of the properties for the actual data are also a bit confusing where you have value, text, displaytext etc. All returning slightly different things so you sort of have to just spray and pray and see which one works.

If EPPlus didn’t exist, and Syncfusion wasn’t fantastically overpriced, this library would actually be pretty good.

TL;DR;

Use EPPlus. https://github.com/JanKallman/EPPlus

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.

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.

  • Remove From My Forums
  • Question

  • Hi,

    I want to write a program to access cells in an excel file?

    How can I do that?

    Thanks

Answers

  • Try this code!

    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open("your excel file path", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); Worksheet sheet = (Worksheet)wb.Sheets["Sheet name to read"]; Range excelRange = sheet.UsedRange; foreach (Microsoft.Office.Interop.Excel.Range row in excelRange.Rows) { int rowNumber = row.Row; string[] A4D4 = GetRange("A" + rowNumber + ":F" + rowNumber + "", sheet); } public string[] GetRange(string range, Worksheet excelWorksheet) { Microsoft.Office.Interop.Excel.Range workingRangeCells = excelWorksheet.get_Range(range, Type.Missing); //workingRangeCells.Select(); System.Array array = (System.Array)workingRangeCells.Cells.Value2; string[] arrayS = this.ConvertToStringArray(array); return arrayS; }


    • Edited by

      Monday, September 5, 2011 6:40 AM

    • Marked as answer by
      Martin_Xie
      Monday, September 19, 2011 11:49 AM

  • Hi DarkSeeker,

    Try this:

    static void Main(string[] args)
    {
      IWorkbook workbook = Factory.GetWorkbook(@"C:tmpMyWorkbook.xls");
      IWorksheet worksheet = workbook.Worksheets[0];                 
      IRange a1 = worksheet.Cells["A1"]; 
      object rawValue = a1.Value;    
      string formattedText = a1.Text;             
      Console.WriteLine("rawValue={0} formattedText={1}", rawValue, formattedText);         
    } 

    Regards, http://shwetamannjain.blogspot.com

    • Marked as answer by
      Martin_Xie
      Monday, September 19, 2011 11:50 AM

  • I
    want to write a program to access cells in an excel file?

    Thanks all for your great help and suggestions.

    Hi DarkSeeker,

    Welcome to MSDN Forum.

    Usually, there are 2 approaches to access Office Excel files in .Net.

    1.      
    COM Interop approach as the above said.

    FAQ:  How do I use Excel Automation in .NET

    http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/df02c6d2-e1b5-4731-bb04-2674aed789de

    Add Reference to COM component “Microsoft Excel Object Library” into your project.

    Code sample: Get/Set cell value in Excel Spreadsheet.

    using Microsoft.Office.Interop.Excel;

    object oExcel
    = new Excel.Application;

    object oBook
    = oExcel.Workbooks.Open(«C:\Book1.xls»);
    object
    oSheet =
    oBook.Worksheets(1);
    // e.g. Read value in A2 cell

    string cellValue
    = oSheet.Range(«A2»).Value;
    // e.g. Change value in A2 cell
    oSheet.Range(«A2»).Value
    = «»;
    oBook.SaveAs(«C:\Book1.xls»,
    true);
    oExcel.Quit();

    2.       OleDb Data Provider approach

    Retrieve Excel Sheet data and bind into DataGridView control, and then access particular cells via DataGridView.

    using System.Data;

    using System.Data.OleDb;


    OleDbConnection conn = new
    OleDb.OleDbConnection((«provider=Microsoft.Jet.OLEDB.4.0; »
    + («data source=C:\myData.xls; »
    + «Extended Properties=Excel 8.0;»)));
    // Select the data from Sheet1 of the workbook.
    OleDbDataAdapter ada = new
    OleDbDataAdapter(«select * from Sheet1$]», conn);
    DataSet ds = new
    DataSet();
    ada.Fill(ds);
    dataGridView1.DataSource
    = ds.Tables[0].DefaultView;
    conn.Close();

    // Access particular cells on DataGridView.

    DataGridView1(RowIndex, ColumnIndex)

    DataGridView1.Rows(RowIndex).Cells(ColumnIndex)


    Martin Xie [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Proposed as answer by
      Carmelo La Monica
      Tuesday, September 6, 2011 5:54 AM
    • Marked as answer by
      Martin_Xie
      Monday, September 19, 2011 11:48 AM

Понравилась статья? Поделить с друзьями:
  • С program read excel
  • С новой страницы комбинация клавиш word
  • С program files x86 microsoft office office12 excel exe
  • С нового строки excel
  • С какого знака начинается формула в электронной таблице excel