DEV Community

IronSoftware
IronSoftware

Posted on • Originally published at ironsoftware.com

C# Open Excel Worksheets

Learn how to use C# open Excel Worksheet functions to work with Excel Spreadsheets and open all file types including (.xls, .csv, .tsv, and .xlsx). To open an Excel Worksheet, read its data, and manipulate it programmatically is essential for many who are developing applications. Here's a solution for every developer who wants a method with fewer lines of code and faster response times.

C#:

//by sheet index
WorkSheet ws = wb.WorkSheets[0];
//for the default
WorkSheet ws = wb.DefaultWorkSheet; 
//for the first sheet: 
WorkSheet ws = wb.WorkSheets.First();
//for the first or default sheet:
WorkSheet ws = wb.WorkSheets.FirstOrDefault();
Enter fullscreen mode Exit fullscreen mode

VB:

'by sheet index
Dim ws As WorkSheet = wb.WorkSheets(0)
'for the default
Dim ws As WorkSheet = wb.DefaultWorkSheet
'for the first sheet: 
Dim ws As WorkSheet = wb.WorkSheets.First()
'for the first or default sheet:
Dim ws As WorkSheet = wb.WorkSheets.FirstOrDefault()
Enter fullscreen mode Exit fullscreen mode

1. Access Excel C# Library

Access the Excel C# Library via DLL or install it using your preferred NuGet manager. Once you've accessed the IronXL library and added it to your project, you can use all the functions below to open Excel Worksheets C#.

PM > Install-Package IronXL.Excel


** How to Tutorial**

2. Load Excel File

Use the WorkBook.Load() function from IronXL to load Excel files into the project. This function requires a string parameter, which is the path of the Excel file to be opened. See here:

C#:

WorkBook wb = WorkBook.Load("Path");//Excel file path
Enter fullscreen mode Exit fullscreen mode

VB:

Dim wb As WorkBook = WorkBook.Load("Path") 'Excel file path
Enter fullscreen mode Exit fullscreen mode

The Excel file of the specified path will load in wb. Now, we need to specify the Excel WorkSheet which will be opened.


3. Open Excel WorkSheet

For opening a specific WorkSheet of an Excel file, IronXL provides the WorkBook.GetWorkSheet() function. Using this, we can easily open the WorkSheet by its name:

C#:

WorkSheet ws = WorkBook.GetWorkSheet("SheetName");
Enter fullscreen mode Exit fullscreen mode

VB:

Dim ws As WorkSheet = WorkBook.GetWorkSheet("SheetName")
Enter fullscreen mode Exit fullscreen mode

The specified WorkSheet will open in ws with all its data. There are also a few other ways to open a specific WorkSheet of an Excel file:

C#:

//by sheet index
WorkSheet ws = wb.WorkSheets[0];
//for the default
WorkSheet ws = wb.DefaultWorkSheet; 
//for the first sheet: 
WorkSheet ws = wb.WorkSheets.First();
//for the first or default sheet:
WorkSheet ws = wb.WorkSheets.FirstOrDefault();
Enter fullscreen mode Exit fullscreen mode

VB:

'by sheet index
Dim ws As WorkSheet = wb.WorkSheets(0)
'for the default
Dim ws As WorkSheet = wb.DefaultWorkSheet
'for the first sheet: 
Dim ws As WorkSheet = wb.WorkSheets.First()
'for the first or default sheet:
Dim ws As WorkSheet = wb.WorkSheets.FirstOrDefault()
Enter fullscreen mode Exit fullscreen mode

Now, we just need to get data from the opened Excel WorkSheet.


4. Get Data from WorkSheet

We can get data from an opened Excel WorkSheet in the following ways:

  1. Get a specific cell value of Excel WorkSheet.
  2. Get data in a specific Range.
  3. Get all the data from WorkSheet.

Let's see one by one how to get data in different ways with these examples:

4.1. Get Specific Cell Value

The first approach to getting data from an Excel WorkSheet is to get the specific cell values. It can be accessed like this:

C#:

string val = ws["Cell Address"].ToString();
Enter fullscreen mode Exit fullscreen mode

VB:

Dim val As String = ws("Cell Address").ToString()
Enter fullscreen mode Exit fullscreen mode

ws is the WorkSheet of the Excel file, as we will see in the following examples. Specific cell values can also be accessed by specifying "row index" and "column index."

C#:

string val=ws.Rows[RowIndex].Columns[ColumnIndex].Value.ToString();
Enter fullscreen mode Exit fullscreen mode

VB:

Dim val As String=ws.Rows(RowIndex).Columns(ColumnIndex).Value.ToString()
Enter fullscreen mode Exit fullscreen mode

Let's see an example of how to open an Excel file in our C# project and get specific cell values using both ways:

C#:

using IronXL;
static void Main(string[] args)
{
    //Load Excel file
    WorkBook wb = WorkBook.Load("sample.xlsx");
    //Open WorkSheet
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //Get value By Cell Address
    Int32 int_val= ws["C6"].Int32Value;
    //Get value by Row and Column Address
    string str_val=ws.Rows[3].Columns[1].Value.ToString();
    Console.WriteLine("Getting Value by Cell Address: {0}",int_val);
    Console.WriteLine("Getting Value by Row and Column Indexes: {0}",str_val);
    Console.ReadKey();
}
Enter fullscreen mode Exit fullscreen mode

VB:

Imports IronXL
Shared Sub Main(ByVal args() As String)
    'Load Excel file
    Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
    'Open WorkSheet
    Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
    'Get value By Cell Address
    Dim int_val As Int32= ws("C6").Int32Value
    'Get value by Row and Column Address
    Dim str_val As String=ws.Rows(3).Columns(1).Value.ToString()
    Console.WriteLine("Getting Value by Cell Address: {0}",int_val)
    Console.WriteLine("Getting Value by Row and Column Indexes: {0}",str_val)
    Console.ReadKey()
End Sub
Enter fullscreen mode Exit fullscreen mode

This code displays the following output:

Image 1

Value of Excel file sample.xlsx in row[3].Column[1] and C6 cell:

Image 2

The rows and column index starts from 0.

Open Excel WorkSheets and get the specific call data, and you can read more about how to read Excel data in C# from already open Excel Worksheets.

4.2. Get Data from Specific Range

Now let's see how to get data in a specific range from an opened Excel WorkSheet using IronXL.

IronXL provides an intelligent way to get data in a specific range. We just specify from to to values:

C#:

WorkSheet["From Cell Address : To Cell Address"];
Enter fullscreen mode Exit fullscreen mode

VB:

WorkSheet("From Cell Address : To Cell Address")
Enter fullscreen mode Exit fullscreen mode

Let's see an example of how to use range to get data from an open Excel WorkSheet:

C#:

using IronXL;
static void Main(string[] args)
{
    WorkBook wb = WorkBook.Load("sample.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //specify the range 
    foreach (var cell in ws["B2:B10"])
    {
        Console.WriteLine("value is: {0}", cell.Text);
    }
    Console.ReadKey();
}
Enter fullscreen mode Exit fullscreen mode

VB:

Imports IronXL
Shared Sub Main(ByVal args() As String)
    Dim wb As WorkBook = WorkBook.Load("sample.xlsx")
    Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
    'specify the range 
    For Each cell In ws("B2:B10")
        Console.WriteLine("value is: {0}", cell.Text)
    Next cell
    Console.ReadKey()
End Sub
Enter fullscreen mode Exit fullscreen mode

The above code will pull data from B2 to B10 as follows:

Image 3

We can see the values of the Excel file sample.xlsx, from B2 to B10:

Image 4

4.3. Get Data from Row

We can also describe a range for a specific row. For example:

C#:

WorkSheet["A1:E1"]
Enter fullscreen mode Exit fullscreen mode

VB:

'WorkSheet["A1:E1"]
Enter fullscreen mode Exit fullscreen mode

This will display all values from A1 to E1. Read more about C# Excel Ranges and how to work with different row and column identifications.

4.4. Get All Data from WorkSheet

Getting all the cell data from the open Excel WorkSheet is also easy using IronXL. For this task, we need to access each cell value by row and column indexes. Lets see the following example, in which we will traverse all WorkSheet cells and access its values.

In this example, basically two loops are working: one is for traversing each row of Excel WorkSheet and the other is for traversing each column of a specific row. In this way each cell value can be easily accessed.

C#:

using IronXL;
static void Main(string[] args)
{
    WorkBook wb = WorkBook.Load("sample2.xlsx");
    WorkSheet ws = wb.GetWorkSheet("Sheet1");
    //access all rows of open Excel WorkSheet
    for (int i = 0; i < ws.Rows.Count(); i++)
    {    
        //access all columns of specific row
        for (int j = 0; j < ws.Columns.Count(); j++)
        {
            //Access each cell for specified column
            Console.WriteLine(ws.Rows[i].Columns[j].Value.ToString());
        }
    }
    Console.ReadKey();
}
Enter fullscreen mode Exit fullscreen mode

VB:

Imports IronXL
Shared Sub Main(ByVal args() As String)
    Dim wb As WorkBook = WorkBook.Load("sample2.xlsx")
    Dim ws As WorkSheet = wb.GetWorkSheet("Sheet1")
    'access all rows of open Excel WorkSheet
    For i As Integer = 0 To ws.Rows.Count() - 1
        'access all columns of specific row
        For j As Integer = 0 To ws.Columns.Count() - 1
            'Access each cell for specified column
            Console.WriteLine(ws.Rows(i).Columns(j).Value.ToString())
        Next j
    Next i
    Console.ReadKey()
End Sub
Enter fullscreen mode Exit fullscreen mode

The output of the above code will display each cell value of the complete open Excel WorkSheet.


Top comments (0)