Overview

IronXL Creates C# Excel Files in .NET

IronXL is an intuitive C# & VB Excel API that allows you to read, edit & create Excel spreadsheet files in .NET with lightning fast performance. There is no need to install MS Office or even the Excel Interop.

IronXL fully supports .NET Core, .NET Framework, Xamarin, Mobile, Linux, macOS and Azure.

IronXL Features:

  • Human support directly from our .NET development team
  • Rapid installation with Microsoft Visual Studio
  • FREE for development. Licenses from $749.

Create and Save an Excel File: Quick Code

https://www.nuget.org/packages/IronXL.Excel/

As an alternative, the IronXL.dll can be downloaded and added to your project.

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-1.cs
using IronXL;

// Instantiate a new workbook with the default format XLSX
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);

// Create a new worksheet in the workbook
var workSheet = workBook.CreateWorkSheet("example_sheet");

// Set the value of cell A1 to "Example"
workSheet["A1"].Value = "Example";

// Set the value of cells A2, A3, and A4 to 5
workSheet["A2:A4"].Value = 5;

// Change the background color of cell A5 to light gray
workSheet["A5"].Style.SetBackgroundColor("#f0f0f0");

// Set the font style to bold for cells A5 and A6
workSheet["A5:A6"].Style.Font.Bold = true;

// Set a formula in cell A6 to calculate the sum of cells A2 through A4
workSheet["A6"].Formula = "=SUM(A2:A4)";

// Calculate the formula to ensure the cell displays the result
workSheet.EvaluateAll();

// Check if the calculated value of cell A6 matches the expected sum of A2 through A4
if (workSheet["A6"].IntValue == (workSheet["A2"].IntValue + workSheet["A3"].IntValue + workSheet["A4"].IntValue))
{
    // Output a success message if the test passes
    Console.WriteLine("Basic test passed");
}

// Save the workbook as an XLSX file
workBook.SaveAs("example_workbook.xlsx");
Imports IronXL



' Instantiate a new workbook with the default format XLSX

Private workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)



' Create a new worksheet in the workbook

Private workSheet = workBook.CreateWorkSheet("example_sheet")



' Set the value of cell A1 to "Example"

Private workSheet("A1").Value = "Example"



' Set the value of cells A2, A3, and A4 to 5

Private workSheet("A2:A4").Value = 5



' Change the background color of cell A5 to light gray

workSheet("A5").Style.SetBackgroundColor("#f0f0f0")



' Set the font style to bold for cells A5 and A6

workSheet("A5:A6").Style.Font.Bold = True



' Set a formula in cell A6 to calculate the sum of cells A2 through A4

workSheet("A6").Formula = "=SUM(A2:A4)"



' Calculate the formula to ensure the cell displays the result

workSheet.EvaluateAll()



' Check if the calculated value of cell A6 matches the expected sum of A2 through A4

If workSheet("A6").IntValue = (workSheet("A2").IntValue + workSheet("A3").IntValue + workSheet("A4").IntValue) Then

	' Output a success message if the test passes

	Console.WriteLine("Basic test passed")

End If



' Save the workbook as an XLSX file

workBook.SaveAs("example_workbook.xlsx")
$vbLabelText   $csharpLabel

Step 1

1. Download the FREE IronXL C# Library

Start using IronXL in your project today with a free trial.

First Step:
green arrow pointer


Install by Using NuGet

There are three different ways to install the IronXL NuGet package:

  1. Visual Studio
  2. Developer Command Prompt
  3. Download the NuGet Package directly

Visual Studio

Visual Studio provides the NuGet Package Manager for you to use to install NuGet packages in your projects. You can access it via the Project Menu, or by right clicking your project in the Solution Explorer. Both these options are shown below in Figures 3 and 4.

Project Menu related to Visual Studio

Figure 3Project menu

Right Click Solution Explorer related to Visual Studio

Figure 4Right click Solution Explorer


After you have clicked Manage NuGet Packages from either option, Browse for the IronXL.Excel package and install it as shown in Figure 5.


Install Iron Excel Nuget Package related to Visual Studio

Figure 5Install IronXL.Excel NuGet Package

Developer Command Prompt

Open the Developer Command Prompt and follow these steps to install the IronXL.Excel NuGet package:

  1. Search for your Developer Command Prompt – it is usually under your Visual Studio folder
  2. Type in the following command:
    PM> Install-Package IronXL.Excel
    PM> Install-Package IronXL.Excel
    SHELL
  3. Press Enter
  4. The package will be installed.
  5. Reload your Visual Studio project

Download the NuGet Package directly

In order to download the NuGet package, make use of the next few steps:

  1. Navigate to the following URL: https://www.nuget.org/packages/ironxl.excel/
  2. Click on Download Package
  3. After the package has downloaded, double click it
  4. Reload your Visual Studio project

Install IronXL by Direct Download of the Library

The second way to install IronXL is by downloading it directly from the following URL: https://ironsoftware.com/csharp/excel/

Download Ironxl Library related to Install IronXL by Direct Download of the Library

Figure 6Download IronXL library

Reference the Library in your project by using the next steps:

  1. Right click the Solution in the Solution Explorer
  2. Select References
  3. Browse for the IronXL.dll library
  4. Click OK

Let's Go!

Now that you’re set up, we can start playing with the awesome features in the IronXL library!


How to Tutorials

2. Create an ASP.NET Project

Make use of the following steps to create an ASP.NET Website:

  1. Open Visual Studio
  2. Click File > New Project
  3. Select Web under Visual C# in the Project type listbox
  4. Select ASP.NET Web Application, as shown next


New Project Asp Net related to 2. Create an ASP.NET Project

Figure 1New Project

  1. Click OK
  2. On the next screen, select Web Forms as shown in Figure 2 underneath

Web Form related to 2. Create an ASP.NET Project

Figure 2Web Forms

  1. Click OK

Now we have something to work with. Install IronXL to start customizing your file.


3. Create an Excel Workbook

It cannot be simpler to create a new Excel Workbook using IronXL! It is one line of code! Yes, really:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-2.cs
// Import necessary namespaces for dealing with Excel files
using GemBox.Spreadsheet;

// The main code execution starts here.

// Initialize GemBox Spreadsheet by setting the license. 
// You can replace "FREE-LIMITED-KEY" with your own license key if you have one.
SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

// Create a new Excel file represented by a Workbook object.
// GemBox.Spreadsheet provides a simple way to create, read, write, and manipulate Excel spreadsheet files.
var workbook = new ExcelFile();

// Add a new worksheet to the workbook.
// In this example, we'll create a single worksheet named "Sheet1".
var worksheet = workbook.Worksheets.Add("Sheet1");

// Example of writing data to cells in the worksheet.
// Let's set the value of the first cell (A1) in the worksheet to "Hello, World!".
worksheet.Cells["A1"].Value = "Hello, World!";

// Save the workbook to a file in Excel format, such as XLSX.
// You can adjust the path and filename as needed for your application.
workbook.Save("output.xlsx");

// Note:
// - GemBox.Spreadsheet is a third-party library used for processing Excel files without needing Excel installed.
// - The code might require adding the GemBox.Spreadsheet library to your project through NuGet or direct download.
// - Ensure that you have the correct setup and licensing to avoid any runtime issues.
' Import necessary namespaces for dealing with Excel files

Imports GemBox.Spreadsheet



' The main code execution starts here.



' Initialize GemBox Spreadsheet by setting the license. 

' You can replace "FREE-LIMITED-KEY" with your own license key if you have one.

SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY")



' Create a new Excel file represented by a Workbook object.

' GemBox.Spreadsheet provides a simple way to create, read, write, and manipulate Excel spreadsheet files.

Dim workbook = New ExcelFile()



' Add a new worksheet to the workbook.

' In this example, we'll create a single worksheet named "Sheet1".

Dim worksheet = workbook.Worksheets.Add("Sheet1")



' Example of writing data to cells in the worksheet.

' Let's set the value of the first cell (A1) in the worksheet to "Hello, World!".

worksheet.Cells("A1").Value = "Hello, World!"



' Save the workbook to a file in Excel format, such as XLSX.

' You can adjust the path and filename as needed for your application.

workbook.Save("output.xlsx")



' Note:

' - GemBox.Spreadsheet is a third-party library used for processing Excel files without needing Excel installed.

' - The code might require adding the GemBox.Spreadsheet library to your project through NuGet or direct download.

' - Ensure that you have the correct setup and licensing to avoid any runtime issues.
$vbLabelText   $csharpLabel

Both XLS (older Excel file version) and XLSX (current and newer file version) file formats can be created with IronXL.

3.1. Set a Default Worksheet

And, it’s even simpler to create a default Worksheet:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-3.cs
// This C# code snippet assumes that there's a defined Workbook class
// with a CreateWorkSheet method. It demonstrates the creation of a 
// worksheet in a workbook using a simple simulation for educational purposes.

using System;

namespace WorkbookExample
{
    // Simulating a Workbook class for demonstration purposes.
    public class Workbook
    {
        // Method to create a worksheet given a name.
        public Worksheet CreateWorkSheet(string name)
        {
            // Validation check: Ensure the name is not null or empty.
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("Worksheet name cannot be null or empty.");
            }

            // Creating a new Worksheet object with the provided name.
            Console.WriteLine($"Worksheet '{name}' created successfully.");
            return new Worksheet() { Name = name };
        }
    }

    // Simulating a Worksheet class for demonstration purposes.
    public class Worksheet
    {
        // Property to store the name of the worksheet.
        public string Name { get; set; }
    }
}

// This part of the code demonstrates the use of Workbook and Worksheet classes.
// The following code is executed at the top-level and demonstrates creating a worksheet.
Workbook workbook = new Workbook(); // Create a new Workbook instance.
Worksheet worksheet = workbook.CreateWorkSheet("2020 Budget"); // Create a new worksheet with a specified name.
' This C# code snippet assumes that there's a defined Workbook class

' with a CreateWorkSheet method. It demonstrates the creation of a 

' worksheet in a workbook using a simple simulation for educational purposes.



Imports System



Namespace WorkbookExample

	' Simulating a Workbook class for demonstration purposes.

	Public Class Workbook

		' Method to create a worksheet given a name.

		Public Function CreateWorkSheet(ByVal name As String) As Worksheet

			' Validation check: Ensure the name is not null or empty.

			If String.IsNullOrWhiteSpace(name) Then

				Throw New ArgumentException("Worksheet name cannot be null or empty.")

			End If



			' Creating a new Worksheet object with the provided name.

			Console.WriteLine($"Worksheet '{name}' created successfully.")

			Return New Worksheet() With {.Name = name}

		End Function

	End Class



	' Simulating a Worksheet class for demonstration purposes.

	Public Class Worksheet

		' Property to store the name of the worksheet.

		Public Property Name() As String

	End Class

End Namespace



' This part of the code demonstrates the use of Workbook and Worksheet classes.

' The following code is executed at the top-level and demonstrates creating a worksheet.

Private workbook As New Workbook() ' Create a new Workbook instance.

Private worksheet As Worksheet = workbook.CreateWorkSheet("2020 Budget") ' Create a new worksheet with a specified name.
$vbLabelText   $csharpLabel

"Sheet" in the above code snippet represents the worksheet and you can use it to set cell values and almost everything Excel can do.

In case you are confused about the difference between a Workbook and a Worksheet, let me explain:

A Workbook contains Worksheets. This means that you can add as many Worksheets as you like into one Workbook. In a later article, I will explain how to do this. A Worksheet contains Rows and Columns. The intersection of a Row and a Column is called a Cell, and this is what you will manipulate whilst working with Excel.


4. Set Cell Values

4.1. Set Cell Values Manually

To set cell values manually, you simply indicate what cell you are working with, and set its value, as in the following example:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-4.cs
// This code assigns the names of the months of the year, from January to December, 
// to the first row in a worksheet, specifically in cells A1 through L1. 
// It assumes that `workSheet` is an instance of a worksheet object, such as one from a 
// spreadsheet library like EPPlus.

workSheet.Cells["A1"].Value = "January";   // Set cell A1 to "January"
workSheet.Cells["B1"].Value = "February";  // Set cell B1 to "February"
workSheet.Cells["C1"].Value = "March";     // Set cell C1 to "March"
workSheet.Cells["D1"].Value = "April";     // Set cell D1 to "April"
workSheet.Cells["E1"].Value = "May";       // Set cell E1 to "May"
workSheet.Cells["F1"].Value = "June";      // Set cell F1 to "June"
workSheet.Cells["G1"].Value = "July";      // Set cell G1 to "July"
workSheet.Cells["H1"].Value = "August";    // Set cell H1 to "August"
workSheet.Cells["I1"].Value = "September"; // Set cell I1 to "September"
workSheet.Cells["J1"].Value = "October";   // Set cell J1 to "October"
workSheet.Cells["K1"].Value = "November";  // Set cell K1 to "November"
workSheet.Cells["L1"].Value = "December";  // Set cell L1 to "December"
' This code assigns the names of the months of the year, from January to December, 

' to the first row in a worksheet, specifically in cells A1 through L1. 

' It assumes that `workSheet` is an instance of a worksheet object, such as one from a 

' spreadsheet library like EPPlus.



workSheet.Cells("A1").Value = "January" ' Set cell A1 to "January"

workSheet.Cells("B1").Value = "February" ' Set cell B1 to "February"

workSheet.Cells("C1").Value = "March" ' Set cell C1 to "March"

workSheet.Cells("D1").Value = "April" ' Set cell D1 to "April"

workSheet.Cells("E1").Value = "May" ' Set cell E1 to "May"

workSheet.Cells("F1").Value = "June" ' Set cell F1 to "June"

workSheet.Cells("G1").Value = "July" ' Set cell G1 to "July"

workSheet.Cells("H1").Value = "August" ' Set cell H1 to "August"

workSheet.Cells("I1").Value = "September" ' Set cell I1 to "September"

workSheet.Cells("J1").Value = "October" ' Set cell J1 to "October"

workSheet.Cells("K1").Value = "November" ' Set cell K1 to "November"

workSheet.Cells("L1").Value = "December" ' Set cell L1 to "December"
$vbLabelText   $csharpLabel

Here, I have populated Columns A to L, and the first row of each to a name of a different month.

4.2. Set Cell Values Dynamically

Setting values dynamically is almost similar to the previous code segment. The nice thing about this is that you do not have to hard-code the cell location. In the next code example, you will create a new Random object to create random numbers, and then make use of a for loop to iterate through the range of cells you’d like to populate with values.

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-5.cs
// Import relevant namespaces if needed

using System;

// Assume 'workSheet' here is an instance of a class that supports indexing and has a .Value property,
// such as a cell in an Excel sheet. 

// Initialize a random number generator
Random r = new Random();

// This loop populates cells in a worksheet with random numbers
// The numbers in each column increment the range by 1000
for (int i = 2; i <= 11; i++)
{
    // Assign a random number between 1 (inclusive) and 1000 (exclusive) to cell A[i]
    workSheet[$"A{i}"].Value = r.Next(1, 1000);

    // Assign a random number between 1000 (inclusive) and 2000 (exclusive) to cell B[i]
    workSheet[$"B{i}"].Value = r.Next(1000, 2000);

    // Assign a random number between 2000 (inclusive) and 3000 (exclusive) to cell C[i]
    workSheet[$"C{i}"].Value = r.Next(2000, 3000);

    // Assign a random number between 3000 (inclusive) and 4000 (exclusive) to cell D[i]
    workSheet[$"D{i}"].Value = r.Next(3000, 4000);

    // Assign a random number between 4000 (inclusive) and 5000 (exclusive) to cell E[i]
    workSheet[$"E{i}"].Value = r.Next(4000, 5000);

    // Assign a random number between 5000 (inclusive) and 6000 (exclusive) to cell F[i]
    workSheet[$"F{i}"].Value = r.Next(5000, 6000);

    // Assign a random number between 6000 (inclusive) and 7000 (exclusive) to cell G[i]
    workSheet[$"G{i}"].Value = r.Next(6000, 7000);

    // Assign a random number between 7000 (inclusive) and 8000 (exclusive) to cell H[i]
    workSheet[$"H{i}"].Value = r.Next(7000, 8000);

    // Assign a random number between 8000 (inclusive) and 9000 (exclusive) to cell I[i]
    workSheet[$"I{i}"].Value = r.Next(8000, 9000);

    // Assign a random number between 9000 (inclusive) and 10000 (exclusive) to cell J[i]
    workSheet[$"J{i}"].Value = r.Next(9000, 10000);

    // Assign a random number between 10000 (inclusive) and 11000 (exclusive) to cell K[i]
    workSheet[$"K{i}"].Value = r.Next(10000, 11000);

    // Assign a random number between 11000 (inclusive) and 12000 (exclusive) to cell L[i]
    workSheet[$"L{i}"].Value = r.Next(11000, 12000);
}
' Import relevant namespaces if needed



Imports System



' Assume 'workSheet' here is an instance of a class that supports indexing and has a .Value property,

' such as a cell in an Excel sheet. 



' Initialize a random number generator

Private r As New Random()



' This loop populates cells in a worksheet with random numbers

' The numbers in each column increment the range by 1000

For i As Integer = 2 To 11

	' Assign a random number between 1 (inclusive) and 1000 (exclusive) to cell A[i]

	workSheet($"A{i}").Value = r.Next(1, 1000)



	' Assign a random number between 1000 (inclusive) and 2000 (exclusive) to cell B[i]

	workSheet($"B{i}").Value = r.Next(1000, 2000)



	' Assign a random number between 2000 (inclusive) and 3000 (exclusive) to cell C[i]

	workSheet($"C{i}").Value = r.Next(2000, 3000)



	' Assign a random number between 3000 (inclusive) and 4000 (exclusive) to cell D[i]

	workSheet($"D{i}").Value = r.Next(3000, 4000)



	' Assign a random number between 4000 (inclusive) and 5000 (exclusive) to cell E[i]

	workSheet($"E{i}").Value = r.Next(4000, 5000)



	' Assign a random number between 5000 (inclusive) and 6000 (exclusive) to cell F[i]

	workSheet($"F{i}").Value = r.Next(5000, 6000)



	' Assign a random number between 6000 (inclusive) and 7000 (exclusive) to cell G[i]

	workSheet($"G{i}").Value = r.Next(6000, 7000)



	' Assign a random number between 7000 (inclusive) and 8000 (exclusive) to cell H[i]

	workSheet($"H{i}").Value = r.Next(7000, 8000)



	' Assign a random number between 8000 (inclusive) and 9000 (exclusive) to cell I[i]

	workSheet($"I{i}").Value = r.Next(8000, 9000)



	' Assign a random number between 9000 (inclusive) and 10000 (exclusive) to cell J[i]

	workSheet($"J{i}").Value = r.Next(9000, 10000)



	' Assign a random number between 10000 (inclusive) and 11000 (exclusive) to cell K[i]

	workSheet($"K{i}").Value = r.Next(10000, 11000)



	' Assign a random number between 11000 (inclusive) and 12000 (exclusive) to cell L[i]

	workSheet($"L{i}").Value = r.Next(11000, 12000)

Next i
$vbLabelText   $csharpLabel

Every cell from A2 to L11 contains a unique value that was randomly generated.

Talking about dynamic values, how about learning how to dynamically add data into cells directly from a database? The next code snippet quickly shows how this is done, assuming you have set up your database connections correctly.

4.3. Add Directly from a Database

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-6.cs
// Import necessary libraries
using System;
using System.Data;
using System.Data.SqlClient;
using OfficeOpenXml; // Assuming usage of EPPlus for Excel operations

// Define and initialize database objects to populate data from the database
string connectionString; // Stores the connection string to connect to the database
string sqlQuery; // Stores the SQL query used to retrieve data from the database
DataSet dataSet = new DataSet("DataSetName"); // DataSet to hold the retrieved data
SqlConnection connection; // SqlConnection object for database connection
SqlDataAdapter dataAdapter; // SqlDataAdapter for executing the query and filling the DataSet

// Set the database connection string 
connectionString = @"Data Source=Server_Name;Initial Catalog=Database_Name;User ID=User_ID;Password=Password";

// Define the SQL Query to obtain data
sqlQuery = "SELECT Field_Names FROM Table_Name";

// Initialize the connection and data adapter objects
connection = new SqlConnection(connectionString);
dataAdapter = new SqlDataAdapter(sqlQuery, connection);

// Open the connection and fill the DataSet with data
try
{
    connection.Open(); // Open the connection to the database
    dataAdapter.Fill(dataSet); // Execute the query and fill the DataSet
}
catch (Exception ex)
{
    // Handle potential exceptions, such as database connection errors
    Console.WriteLine("An error occurred: " + ex.Message);
}
finally
{
    // Ensure the connection is closed after the operation
    if (connection != null)
    {
        connection.Close(); // Close the database connection
    }
}

// Assuming 'workSheet' is an EPPlus ExcelWorksheet object set up elsewhere for Excel operations
// Loop through the contents of the DataSet
foreach (DataTable table in dataSet.Tables)
{
    int rowCount = table.Rows.Count; // Get the number of rows in the table
    for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) // Iterate through each row in the table
    {
        // Use the table row index plus an offset to map onto the worksheet row
        int worksheetRowIndex = rowIndex + 12; // Adjust starting index as needed

        // Map each field value to a corresponding cell in the worksheet
        workSheet.Cells["A" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_1"].ToString();
        workSheet.Cells["B" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_2"].ToString();
        workSheet.Cells["C" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_3"].ToString();
        workSheet.Cells["D" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_4"].ToString();
        workSheet.Cells["E" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_5"].ToString();
        workSheet.Cells["F" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_6"].ToString();
        workSheet.Cells["G" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_7"].ToString();
        workSheet.Cells["H" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_8"].ToString();
        workSheet.Cells["I" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_9"].ToString();
        workSheet.Cells["J" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_10"].ToString();
        workSheet.Cells["K" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_11"].ToString();
        workSheet.Cells["L" + worksheetRowIndex].Value = table.Rows[rowIndex]["Field_Name_12"].ToString();
    }
}
' Import necessary libraries

Imports System

Imports System.Data

Imports System.Data.SqlClient

Imports OfficeOpenXml ' Assuming usage of EPPlus for Excel operations



' Define and initialize database objects to populate data from the database

Private connectionString As String ' Stores the connection string to connect to the database

Private sqlQuery As String ' Stores the SQL query used to retrieve data from the database

Private dataSet As New DataSet("DataSetName") ' DataSet to hold the retrieved data

Private connection As SqlConnection ' SqlConnection object for database connection

Private dataAdapter As SqlDataAdapter ' SqlDataAdapter for executing the query and filling the DataSet



' Set the database connection string 

connectionString = "Data Source=Server_Name;Initial Catalog=Database_Name;User ID=User_ID;Password=Password"



' Define the SQL Query to obtain data

sqlQuery = "SELECT Field_Names FROM Table_Name"



' Initialize the connection and data adapter objects

connection = New SqlConnection(connectionString)

dataAdapter = New SqlDataAdapter(sqlQuery, connection)



' Open the connection and fill the DataSet with data

Try

	connection.Open() ' Open the connection to the database

	dataAdapter.Fill(dataSet) ' Execute the query and fill the DataSet

Catch ex As Exception

	' Handle potential exceptions, such as database connection errors

	Console.WriteLine("An error occurred: " & ex.Message)

Finally

	' Ensure the connection is closed after the operation

	If connection IsNot Nothing Then

		connection.Close() ' Close the database connection

	End If

End Try



' Assuming 'workSheet' is an EPPlus ExcelWorksheet object set up elsewhere for Excel operations

' Loop through the contents of the DataSet

For Each table As DataTable In dataSet.Tables

	Dim rowCount As Integer = table.Rows.Count ' Get the number of rows in the table

	For rowIndex As Integer = 0 To rowCount - 1 ' Iterate through each row in the table

		' Use the table row index plus an offset to map onto the worksheet row

		Dim worksheetRowIndex As Integer = rowIndex + 12 ' Adjust starting index as needed



		' Map each field value to a corresponding cell in the worksheet

		workSheet.Cells("A" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_1").ToString()

		workSheet.Cells("B" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_2").ToString()

		workSheet.Cells("C" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_3").ToString()

		workSheet.Cells("D" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_4").ToString()

		workSheet.Cells("E" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_5").ToString()

		workSheet.Cells("F" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_6").ToString()

		workSheet.Cells("G" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_7").ToString()

		workSheet.Cells("H" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_8").ToString()

		workSheet.Cells("I" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_9").ToString()

		workSheet.Cells("J" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_10").ToString()

		workSheet.Cells("K" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_11").ToString()

		workSheet.Cells("L" & worksheetRowIndex).Value = table.Rows(rowIndex)("Field_Name_12").ToString()

	Next rowIndex

Next table
$vbLabelText   $csharpLabel

You simply have to set the Value property of the particular cell to the Field name to be entered into the cell.


5. Apply Formatting

5.1. Set Background Colors of Cells

To set the background color of a cell or a range of cells, you simply need a line of code that looks like the following:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-7.cs
// It appears that you are working with an Excel library, most likely EPPlus, to manipulate Excel spreadsheets.
// The code below assumes that you are iterating over a worksheet object to set the background color
// of the specified range. Ensure that you have included the necessary using directives for your library.

using OfficeOpenXml; // Assuming you are using EPPlus or similar library
using OfficeOpenXml.Style; // For Excel fill styles
using System.Drawing; // For the Color structure

// Assuming 'workSheet' is a valid ExcelWorksheet object that you want to modify
// This code sets the background color of the range from cell A1 to L1 on the worksheet.

void SetBackgroundColor(ExcelWorksheet workSheet)
{
    // Convert the hexadecimal color code to a Color object.
    Color backgroundColor = ColorTranslator.FromHtml("#d3d3d3");

    // Set the background color for the specified range on the worksheet.
    workSheet.Cells["A1:L1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
    workSheet.Cells["A1:L1"].Style.Fill.BackgroundColor.SetColor(backgroundColor);
}

// Note: The above code assumes you have an existing Excel package and worksheet.
// Make sure that your project includes the EPPlus NuGet package and any relevant libraries.
' It appears that you are working with an Excel library, most likely EPPlus, to manipulate Excel spreadsheets.

' The code below assumes that you are iterating over a worksheet object to set the background color

' of the specified range. Ensure that you have included the necessary using directives for your library.



Imports OfficeOpenXml ' Assuming you are using EPPlus or similar library

Imports OfficeOpenXml.Style ' For Excel fill styles

Imports System.Drawing ' For the Color structure



' Assuming 'workSheet' is a valid ExcelWorksheet object that you want to modify

' This code sets the background color of the range from cell A1 to L1 on the worksheet.



Private Sub SetBackgroundColor(ByVal workSheet As ExcelWorksheet)

	' Convert the hexadecimal color code to a Color object.

	Dim backgroundColor As Color = ColorTranslator.FromHtml("#d3d3d3")



	' Set the background color for the specified range on the worksheet.

	workSheet.Cells("A1:L1").Style.Fill.PatternType = ExcelFillStyle.Solid

	workSheet.Cells("A1:L1").Style.Fill.BackgroundColor.SetColor(backgroundColor)

End Sub



' Note: The above code assumes you have an existing Excel package and worksheet.

' Make sure that your project includes the EPPlus NuGet package and any relevant libraries.
$vbLabelText   $csharpLabel

This sets the background color of the range of cells to gray. The color is in RGB (Red, Green, Blue) format where the first two characters represent Red, the next two, Green and the last two, Blue. The values range from 0 to 9, then A to F (Hexadecimal).

5.2. Create Borders

Creating borders with IronXL is very simple, as shown next:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-8.cs
// Ensure that the IronXL library is referenced in your project.
using IronXL;

// The following code sets the border styles and colors for different cell ranges in an Excel worksheet.

// Set the top border color of the range A1:L1 to black.
workSheet["A1:L1"].Style.TopBorder.SetColor("#000000");

// Set the bottom border color of the range A1:L1 to black.
workSheet["A1:L1"].Style.BottomBorder.SetColor("#000000");

// Set the right border color of the range L2:L11 to black.
workSheet["L2:L11"].Style.RightBorder.SetColor("#000000");

// Set the right border type of the range L2:L11 to Medium.
workSheet["L2:L11"].Style.RightBorder.Type = IronXL.Styles.BorderType.Medium;

// Set the bottom border color of the range A11:L11 to black.
workSheet["A11:L11"].Style.BottomBorder.SetColor("#000000");

// Set the bottom border type of the range A11:L11 to Medium.
workSheet["A11:L11"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Medium;
' Ensure that the IronXL library is referenced in your project.

Imports IronXL



' The following code sets the border styles and colors for different cell ranges in an Excel worksheet.



' Set the top border color of the range A1:L1 to black.

workSheet("A1:L1").Style.TopBorder.SetColor("#000000")



' Set the bottom border color of the range A1:L1 to black.

workSheet("A1:L1").Style.BottomBorder.SetColor("#000000")



' Set the right border color of the range L2:L11 to black.

workSheet("L2:L11").Style.RightBorder.SetColor("#000000")



' Set the right border type of the range L2:L11 to Medium.

workSheet("L2:L11").Style.RightBorder.Type = IronXL.Styles.BorderType.Medium



' Set the bottom border color of the range A11:L11 to black.

workSheet("A11:L11").Style.BottomBorder.SetColor("#000000")



' Set the bottom border type of the range A11:L11 to Medium.

workSheet("A11:L11").Style.BottomBorder.Type = IronXL.Styles.BorderType.Medium
$vbLabelText   $csharpLabel

In the above code I have set black Top and Bottom borders to Cells A1 to L1, then I have set the Right border to cells L2 to L11 and the style of the border is set to Medium. Lastly, I have set the Bottom border for cells A11 to L11


6. Use Formulas in Cells

I keep saying that IronXL makes everything so easy, but it really does, and I can’t highlight it enough! The following code allows you to use formulas:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-9.cs
// IronXL is a library used for reading, writing, and modifying Excel files within .NET applications.
// This code snippet demonstrates how to use IronXL's built-in aggregation functions 
// to perform operations such as Sum, Avg, Max, and Min on specific ranges of an Excel worksheet 
// and assign the resulting values to specific cells.

// Ensure the IronXL namespace is referenced.
using IronXL;

// Load an existing workbook.
var workbook = WorkBook.Load("Filename.xlsx");

// Select the worksheet to perform operations on using the worksheet's name.
var workSheet = workbook.GetWorkSheet("SheetName");

// Calculate the sum of values in the range A2:A11.
decimal sum = workSheet["A2:A11"].Sum();

// Calculate the average of values in the range B2:B11.
decimal avg = workSheet["B2:B11"].Avg();

// Find the maximum value in the range C2:C11.
decimal max = workSheet["C2:C11"].Max();

// Find the minimum value in the range D2:D11.
decimal min = workSheet["D2:D11"].Min();

// Assign the calculated values to specific cells in the worksheet.
workSheet["A12"].Value = sum;
workSheet["B12"].Value = avg;
workSheet["C12"].Value = max;
workSheet["D12"].Value = min;

// Save changes to the workbook. Ensure you have write permissions to save the file.
workbook.SaveAs("UpdatedFilename.xlsx");
' IronXL is a library used for reading, writing, and modifying Excel files within .NET applications.

' This code snippet demonstrates how to use IronXL's built-in aggregation functions 

' to perform operations such as Sum, Avg, Max, and Min on specific ranges of an Excel worksheet 

' and assign the resulting values to specific cells.



' Ensure the IronXL namespace is referenced.

Imports IronXL



' Load an existing workbook.

Private workbook = WorkBook.Load("Filename.xlsx")



' Select the worksheet to perform operations on using the worksheet's name.

Private workSheet = workbook.GetWorkSheet("SheetName")



' Calculate the sum of values in the range A2:A11.

Private sum As Decimal = workSheet("A2:A11").Sum()



' Calculate the average of values in the range B2:B11.

Private avg As Decimal = workSheet("B2:B11").Avg()



' Find the maximum value in the range C2:C11.

Private max As Decimal = workSheet("C2:C11").Max()



' Find the minimum value in the range D2:D11.

Private min As Decimal = workSheet("D2:D11").Min()



' Assign the calculated values to specific cells in the worksheet.

Private workSheet("A12").Value = sum

Private workSheet("B12").Value = avg

Private workSheet("C12").Value = max

Private workSheet("D12").Value = min



' Save changes to the workbook. Ensure you have write permissions to save the file.

workbook.SaveAs("UpdatedFilename.xlsx")
$vbLabelText   $csharpLabel

What’s nice about this is the fact that you can set the data type of the cell thus the result of the formula. The above code shows how to use the SUM (sums values), AVG (averages values), MAX (gets the highest value) and MIN (gets the lowest value) formulas.


7. Set Worksheet and Print Properties

7.1. Set Worksheet Properties

Worksheet properties include freezing rows and columns and protecting the worksheet with a password. This is shown next:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-10.cs
// The code below demonstrates how to protect an Excel worksheet with a password 
// and freeze the top row using C#. The assumption is that a library handling 
// Excel operations is being used, such as EPPlus or a similar library.

// Ensure you have included the correct library that handles worksheet operations.
// Below is a demonstration using the EPPlus library as an example.

using OfficeOpenXml;  // Example of a needed namespace if using EPPlus
using OfficeOpenXml.Excel;  // Ensure the correct namespace is used

// Assuming 'workSheet' is a valid reference to an Excel worksheet in your code,
// the following actions will protect the worksheet with a password
// and freeze the top row.

// Protect the worksheet with the specified password.
workSheet.Protection.SetPassword("Password");
// Note: Depending on the library, the method to set a password might differ.
// In EPPlus, it's necessary to set different attributes of the protection.

// The following code freezes the first row, keeping it visible while scrolling vertically.
// Note: Parameters may vary depending on the library. For EPPlus, it might look like this.
workSheet.View.FreezePanes(2, 1);  // EPPlus uses a 1-based index, so '2' freezes the first row.

// Note: Always refer to the documentation of the library being used for the correct method calls and usage.
' The code below demonstrates how to protect an Excel worksheet with a password 

' and freeze the top row using C#. The assumption is that a library handling 

' Excel operations is being used, such as EPPlus or a similar library.



' Ensure you have included the correct library that handles worksheet operations.

' Below is a demonstration using the EPPlus library as an example.



Imports OfficeOpenXml ' Example of a needed namespace if using EPPlus

Imports OfficeOpenXml.Excel ' Ensure the correct namespace is used



' Assuming 'workSheet' is a valid reference to an Excel worksheet in your code,

' the following actions will protect the worksheet with a password

' and freeze the top row.



' Protect the worksheet with the specified password.

workSheet.Protection.SetPassword("Password")

' Note: Depending on the library, the method to set a password might differ.

' In EPPlus, it's necessary to set different attributes of the protection.



' The following code freezes the first row, keeping it visible while scrolling vertically.

' Note: Parameters may vary depending on the library. For EPPlus, it might look like this.

workSheet.View.FreezePanes(2, 1) ' EPPlus uses a 1-based index, so '2' freezes the first row.



' Note: Always refer to the documentation of the library being used for the correct method calls and usage.
$vbLabelText   $csharpLabel

The first row is frozen and will not scroll along with the rest of the Worksheet. The worksheet is also protected from any edits with a password. Figures 7 and 8 shows this in action.

Freeze Panes related to 7.1. Set Worksheet Properties

Figure 7Freeze Panes

Protected Worksheet related to 7.1. Set Worksheet Properties

Figure 8Protected Worksheet

7.2. Set Page and Print Properties

You can set Page properties such as the Orientation of the page, the size of the page as well as the PrintArea to name a few.

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-11.cs
// Assuming that `workSheet` is an instance of a worksheet from a library like IronXL.
// This code snippet configures the print settings of the worksheet.

using IronXL;
using IronXL.Styles;
using IronXL.Printing;

// The following code configures the print settings for a worksheet.
// First, the print area is set, then the orientation and paper size are configured.

// Set the print area of the worksheet to the range A1 to L12.
// This ensures that only this specific area is included when printing the worksheet.
workSheet.SetPrintArea("A1:L12");

// Set the print orientation to Landscape. 
// This will print the worksheet in landscape format, which is wider than it is tall.
workSheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape;

// Set the paper size to A4. 
// This specifies that the worksheet should be printed on A4 paper, a common international paper size.
workSheet.PrintSetup.PaperSize = PaperSize.A4;
' Assuming that `workSheet` is an instance of a worksheet from a library like IronXL.

' This code snippet configures the print settings of the worksheet.



Imports IronXL

Imports IronXL.Styles

Imports IronXL.Printing



' The following code configures the print settings for a worksheet.

' First, the print area is set, then the orientation and paper size are configured.



' Set the print area of the worksheet to the range A1 to L12.

' This ensures that only this specific area is included when printing the worksheet.

workSheet.SetPrintArea("A1:L12")



' Set the print orientation to Landscape. 

' This will print the worksheet in landscape format, which is wider than it is tall.

workSheet.PrintSetup.PrintOrientation = PrintOrientation.Landscape



' Set the paper size to A4. 

' This specifies that the worksheet should be printed on A4 paper, a common international paper size.

workSheet.PrintSetup.PaperSize = PaperSize.A4
$vbLabelText   $csharpLabel

The Print area gets set to A1 to L12. The Orientation gets set to Landscape and the paper size gets set to A4.

Print Setup related to 7.2. Set Page and Print Properties

Figure 9Print Setup


8. Save Workbook

To save the Workbook, use the following code:

:path=/static-assets/excel/content-code-examples/tutorials/create-excel-file-net-12.cs
// This snippet demonstrates saving a workbook as an Excel file named "Budget.xlsx".
// Please ensure that you have added necessary references to the Excel library, 
// such as Microsoft.Office.Interop.Excel if using .NET Framework or its 
// equivalent for .NET Core with Excel interop.

using Microsoft.Office.Interop.Excel; // Ensure you include the necessary namespace for Excel interop;

// Create a new instance of Excel Application
Application excelApp = new Application();

// Check if the Excel application instance was created successfully
if (excelApp == null)
{
    Console.WriteLine("Excel is not properly installed on your system.");
    return; // Exit if Excel is not installed
}

// Make Excel visible for debugging. Comment this out if no GUI is needed.
// excelApp.Visible = true;

// Add a new workbook
_Workbook workBook = excelApp.Workbooks.Add();

// ToDo: Add data/manipulate the workbook as needed
// This section should include any logic to populate the workbook with data before saving.
// Example: 
// Worksheet workSheet = (_Worksheet)workBook.Sheets[1];
// workSheet.Cells[1, 1] = "Hello World";

// Save the workbook as a file named "Budget.xlsx"
try
{
    workBook.SaveAs("Budget.xlsx", XlFileFormat.xlWorkbookDefault);
    Console.WriteLine("Workbook saved successfully as Budget.xlsx.");
}
catch (Exception ex)
{
    // Catch any exception that might occur during the save process
    Console.WriteLine("An error occurred while saving the workbook: " + ex.Message);
}
finally
{
    // Properly close the Excel application to release resources
    workBook.Close(false);
    excelApp.Quit();

    // Release COM objects to fully kill the Excel process from running in the background
    System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
    
    // Set variables to null and run garbage collection to clean up the memory
    workBook = null;
    excelApp = null;
    GC.Collect();
}
' This snippet demonstrates saving a workbook as an Excel file named "Budget.xlsx".

' Please ensure that you have added necessary references to the Excel library, 

' such as Microsoft.Office.Interop.Excel if using .NET Framework or its 

' equivalent for .NET Core with Excel interop.



Imports Microsoft.Office.Interop.Excel ' Ensure you include the necessary namespace for Excel interop;



' Create a new instance of Excel Application

Private excelApp As New Application()



' Check if the Excel application instance was created successfully

If excelApp Is Nothing Then

	Console.WriteLine("Excel is not properly installed on your system.")

	Return ' Exit if Excel is not installed

End If



' Make Excel visible for debugging. Comment this out if no GUI is needed.

' excelApp.Visible = true;



' Add a new workbook

Dim workBook As _Workbook = excelApp.Workbooks.Add()



' ToDo: Add data/manipulate the workbook as needed

' This section should include any logic to populate the workbook with data before saving.

' Example: 

' Worksheet workSheet = (_Worksheet)workBook.Sheets[1];

' workSheet.Cells[1, 1] = "Hello World";



' Save the workbook as a file named "Budget.xlsx"

Try

	workBook.SaveAs("Budget.xlsx", XlFileFormat.xlWorkbookDefault)

	Console.WriteLine("Workbook saved successfully as Budget.xlsx.")

Catch ex As Exception

	' Catch any exception that might occur during the save process

	Console.WriteLine("An error occurred while saving the workbook: " & ex.Message)

Finally

	' Properly close the Excel application to release resources

	workBook.Close(False)

	excelApp.Quit()



	' Release COM objects to fully kill the Excel process from running in the background

	System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook)

	System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp)



	' Set variables to null and run garbage collection to clean up the memory

	workBook = Nothing

	excelApp = Nothing

	GC.Collect()

End Try
$vbLabelText   $csharpLabel

Tutorial Quick Access

Brand Visual Studio related to 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 Create Excel File in C# on GitHub
Github Icon related to Tutorial Quick Access
Documentation related to Tutorial Quick Access

Read the XL 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

Frequently Asked Questions

How can I create an Excel file in C# without using Interop?

You can create Excel files in C# without using Interop by using the IronXL library, which supports .NET Framework 4.5 or .NET Core.

What platforms does IronXL support?

IronXL supports .NET Core, .NET Framework, Xamarin, Mobile, Linux, macOS, and Azure.

How do I install IronXL?

IronXL can be installed via NuGet in Visual Studio, through the Developer Command Prompt, or by downloading the package directly.

How do I create a new Excel Workbook?

You can create a new Excel Workbook using a library like IronXL with the code: var workbook = WorkBook.Create();

How can I set cell values in an Excel worksheet?

You can set cell values using libraries such as IronXL by referencing the cell and assigning a value, like so: sheet['A1'].Value = 'Hello, World!';

Can I apply formatting to cells?

Yes, you can apply formatting such as setting background colors and borders using IronXL.

Is it possible to use formulas?

Yes, using IronXL, you can apply Excel formulas in cells, such as SUM, AVERAGE, MAX, and MIN.

How can I protect a worksheet with a password?

You can protect a worksheet by using the Protect method from IronXL and providing a password, like so: sheet.Protect('your_password');

How do I set print properties for a worksheet?

Print properties such as orientation and paper size can be set using libraries like IronXL by utilizing the PrintOptions property of the worksheet.

How do I save an Excel Workbook?

To save a workbook using IronXL, use the SaveAs method and specify the file path: workbook.SaveAs('MyExcelWorkbook.xlsx');

Chaknith Bin
Software Engineer
Chaknith works on IronXL and IronBarcode. He has deep expertise in C# and .NET, helping improve the software and support customers. His insights from user interactions contribute to better products, documentation, and overall experience.