USING IRONXL

How to Create a new Excel Workbook in C#

Published April 29, 2024
Share:

Microsoft Excel is one of the most universal tools for data manipulation and analysis across various industries. In many software projects, there's often a requirement to programmatically engage with Excel files. This could involve tasks such as report generation, managing data imports or exports, or automating specific processes.

In the C# programming language ecosystem, IronXL stands out as a robust library for Excel file manipulation. Whether you're a developer working on a web application, desktop software, or any other C# project, IronXL provides an easy-to-use interface for working with Excel files seamlessly.

How to Create a new Excel Workbook in C#

In this tutorial, we'll learn the process of creating a new workbook using IronXL in C#. We'll walk through the necessary steps, from setting up your development environment to writing the code that generates a new Excel workbook.

By the end of this tutorial, you'll have a solid understanding of how to leverage IronXL to create Excel workbooks programmatically, empowering you to integrate Excel functionality into your C# applications with ease. Let's get started!

What is IronXL?

IronXL is a versatile C# library that allows you to work with Excel documents without the need for Microsoft Office Excel Interop or any Excel Application. It lets you easily read, create, and modify workbooks, format cells, add formulas, and work with both modern and older Excel file formats.

You can validate data, insert images, apply conditional formatting, and create charts without needing Microsoft Office. Developers can build Excel solutions for tasks like financial reports, data dashboards, and inventory management with ease by using IronXL.

Let's begin creating an Excel file in C#.

Step 1: Create a New C# Project

Open Visual Studio and create a new C# Console Application project. Name it as per your preference. You can also create other types of Projects such as ASP.NET MVC, Blazor, MAUI, WEB Forms, Windows Forms, WEB API, etc. This code will work with all project types. I am creating a console application for simplicity and making it relevant for all project types.

Step 2: Install IronXL NuGet Package

To install the IronXL package in your C# project, you can use any of the following ways:

  1. To install IronXL, right-click on your project in Solution Explorer, choose "Manage NuGet Packages," search for IronXL, and then proceed with the installation.

How to Create a new Excel Workbook in C#: Figure 1 - Install IronXL using the Manage NuGet Package for Solution by searching "IronXL" in the search bar of NuGet Package Manager, then select the project and click on the Install button.

  1. Alternatively, you can install IronXL via the Package Manager Console using the following command:
Install-Package IronXL.Excel

This command will download, install, and add assembly reference to our project. Wait for the package to be downloaded and installed. Once the installation is complete, you can start using IronXL in your project to work with Excel files programmatically.

How to Create a new Excel Workbook in C#: Figure 2 - Install IronXL using Package Manager Console command: Install-Package IronXL.Excel

Step 3: Import Necessary Namespace

At the top of your C# file, add the following namespace:

using IronXL;
using IronXL;
Imports IronXL
VB   C#

Step 4: Create a New Excel file

Now, let's write the code to create Excel file:

internal class Program
{
    static void Main(string [] args)
    {
    // Create an XLSX new workbook
        WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX); 
        workBook.Metadata.Author = "Mr. Author"; // Set the author (optional)
        // Add a blank worksheet
        WorkSheet workSheet = workBook.CreateWorkSheet("Sheet1"); 
        // Add data to the new worksheet
        workSheet ["A1"].Value = "Developer Name";
        workSheet ["A2"].Value = "John Grahm";
        workSheet ["A3"].Value = "David Smith";
        workSheet ["A4"].Value = "Rishi Kelkar";
        // Save the excel file as XLS, XLSX, CSV, TSV, JSON, XML, HTML and streams
        workBook.SaveAs("Developers.xlsx");
    }
}
internal class Program
{
    static void Main(string [] args)
    {
    // Create an XLSX new workbook
        WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX); 
        workBook.Metadata.Author = "Mr. Author"; // Set the author (optional)
        // Add a blank worksheet
        WorkSheet workSheet = workBook.CreateWorkSheet("Sheet1"); 
        // Add data to the new worksheet
        workSheet ["A1"].Value = "Developer Name";
        workSheet ["A2"].Value = "John Grahm";
        workSheet ["A3"].Value = "David Smith";
        workSheet ["A4"].Value = "Rishi Kelkar";
        // Save the excel file as XLS, XLSX, CSV, TSV, JSON, XML, HTML and streams
        workBook.SaveAs("Developers.xlsx");
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
	' Create an XLSX new workbook
		Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
		workBook.Metadata.Author = "Mr. Author" ' Set the author (optional)
		' Add a blank worksheet
		Dim workSheet As WorkSheet = workBook.CreateWorkSheet("Sheet1")
		' Add data to the new worksheet
		workSheet ("A1").Value = "Developer Name"
		workSheet ("A2").Value = "John Grahm"
		workSheet ("A3").Value = "David Smith"
		workSheet ("A4").Value = "Rishi Kelkar"
		' Save the excel file as XLS, XLSX, CSV, TSV, JSON, XML, HTML and streams
		workBook.SaveAs("Developers.xlsx")
	End Sub
End Class
VB   C#

The above code demonstrates how to create an Excel file programmatically using IronXL in C#. It starts by creating a new Excel workbook (new instance of Excel file) in the XLSX format, sets author metadata, adds a blank Excel worksheet with the name "Sheet1" using the CreateWorkSheet() method, populates data in cells A1 to A4, and finally saves the workbook as "Developers.xlsx".

IronXL offers a range of functionalities for working with Excel files, including creation, manipulation, and saving in various formats like XLSX, CSV, TSV, JSON, XML, and HTML.

The output is as:

How to Create a new Excel Workbook in C#: Figure 3 - Output: Developers.xlsx

Step 4: Formatting and Styling Excel File

IronXL allows you to format cells, apply font styles, set background colors, and adjust alignment. You can create professional-looking spreadsheets by customizing cell appearance.

// Set Style of Heading
  workSheet ["A1"].Style.BackgroundColor = "#FFFF66";
  workSheet ["A1"].Style.Font.Bold = true;
  // Set Border of Specific Range
  var range = workSheet ["A1:A4"];
  range.Style.BottomBorder.Type = BorderType.Medium;
  range.Style.LeftBorder.Type = BorderType.Medium;
  range.Style.RightBorder.Type = BorderType.Medium;
  range.Style.TopBorder.Type = BorderType.Medium;
// Set Style of Heading
  workSheet ["A1"].Style.BackgroundColor = "#FFFF66";
  workSheet ["A1"].Style.Font.Bold = true;
  // Set Border of Specific Range
  var range = workSheet ["A1:A4"];
  range.Style.BottomBorder.Type = BorderType.Medium;
  range.Style.LeftBorder.Type = BorderType.Medium;
  range.Style.RightBorder.Type = BorderType.Medium;
  range.Style.TopBorder.Type = BorderType.Medium;
' Set Style of Heading
  workSheet ("A1").Style.BackgroundColor = "#FFFF66"
  workSheet ("A1").Style.Font.Bold = True
  ' Set Border of Specific Range
  Dim range = workSheet ("A1:A4")
  range.Style.BottomBorder.Type = BorderType.Medium
  range.Style.LeftBorder.Type = BorderType.Medium
  range.Style.RightBorder.Type = BorderType.Medium
  range.Style.TopBorder.Type = BorderType.Medium
VB   C#

The above code demonstrates how to customize the appearance of specific cells in an Excel worksheet using IronXL in C#. It first sets the background color of cell A1 to a light yellow shade and makes the font bold, effectively styling it as a heading.

Next, it defines a range spanning cells A1 to A4 and sets medium-weight borders along the bottom, left, right, and top edges of this range, enhancing its visual distinction within the worksheet. These styling options allow developers to create visually appealing and organized Excel documents tailored to their specific needs.

The output is as:

How to Create a new Excel Workbook in C#: Figure 4 - Generate Excel with formatting and styling using IronXL.

Step 5: Formula and Calculation

You can add formulas to cells programmatically. IronXL supports a wide range of Excel functions.

// Add a New Column to Display Length of Developer Name
  workSheet ["B1"].Value = "Name Length";
  workSheet ["B1"].Style.BackgroundColor = "#FFFF66";
  workSheet ["B1"].Style.Font.Bold = true;
  workSheet ["B2"].Value = "=LEN(A2)";
  workSheet ["B3"].Value = "=LEN(A3)";
  workSheet ["B4"].Value = "=LEN(A4)";
  workSheet ["A5"].Value = "Sum of Length"; // Total Count of Developers = SUM(B2: B4)
  workSheet ["B5"].Formula = "=SUM(B2:B4)";
// Add a New Column to Display Length of Developer Name
  workSheet ["B1"].Value = "Name Length";
  workSheet ["B1"].Style.BackgroundColor = "#FFFF66";
  workSheet ["B1"].Style.Font.Bold = true;
  workSheet ["B2"].Value = "=LEN(A2)";
  workSheet ["B3"].Value = "=LEN(A3)";
  workSheet ["B4"].Value = "=LEN(A4)";
  workSheet ["A5"].Value = "Sum of Length"; // Total Count of Developers = SUM(B2: B4)
  workSheet ["B5"].Formula = "=SUM(B2:B4)";
' Add a New Column to Display Length of Developer Name
  workSheet ("B1").Value = "Name Length"
  workSheet ("B1").Style.BackgroundColor = "#FFFF66"
  workSheet ("B1").Style.Font.Bold = True
  workSheet ("B2").Value = "=LEN(A2)"
  workSheet ("B3").Value = "=LEN(A3)"
  workSheet ("B4").Value = "=LEN(A4)"
  workSheet ("A5").Value = "Sum of Length" ' Total Count of Developers = SUM(B2: B4)
  workSheet ("B5").Formula = "=SUM(B2:B4)"
VB   C#

The above code illustrates the utilization of formulas and functions in IronXL for calculating the length of developer names and computing the sum of these lengths within an Excel worksheet. Through this demonstration, developers can understand how to integrate formulas and functions within IronXL to perform dynamic calculations and manipulations within Excel worksheets programmatically, offering flexibility and automation in data processing tasks.

Firstly, a header titled "Name Length" is added to cell B1, with styling to highlight its significance. Subsequently, formulas are applied to cells B2, B3, and B4 to calculate the length of each developer's name using the LEN function, referencing the corresponding cell in column A. This enables automatic calculation of name lengths as the developer names change.

Additionally, a total count of developers' name lengths is computed in cell B5 using the SUM function, which adds up the values from cells B2 to B4.

By incorporating these formulas, the worksheet becomes dynamically updated. This use case might not be practical, but this is just for example of using an Excel formula in code.

How to Create a new Excel Workbook in C#: Figure 5 - Excel output with formula and calculation using IronXL.

Conclusion

In summary, this tutorial has demonstrated the process of creating a new Excel workbook in C# using IronXL, a robust library facilitating Excel file manipulation within the C# ecosystem. With IronXL, developers can seamlessly integrate Excel functionality into their applications, from setting up the development environment to generating Excel workbooks programmatically. Alongside its ability to perform tasks like formatting, styling, and applying formulas, IronXL offers a comprehensive feature set for efficient data management and analysis.

For references on how to use IronXL, please visit the documentation page. IronXL also offers a collection of code examples that are helpful to get started.

Developers can explore IronXL through its free trial and purchase, ensuring a seamless transition from evaluation to full-scale implementation. For more details on perpetual licenses, please visit the license page link.

< PREVIOUS
How to parse an Excel file in Python
NEXT >
How to Use C# Excel Font Style

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 1,068,832 View Licenses >