How to create Excel files in C# and VB.NET

Excel is a powerful data management tool widely used across various industries. Yet, creating and managing Excel files programmatically can be complex, especially when dealing with different file formats.

GemBox.Spreadsheet offers an easy-to-use API to create Excel files in formats like XLSX, XLS, XLSB, and ODS without the need to use Microsoft Office Interop. In contrast to some free tools, such as Open XML SDK, which focuses on low-level Excel file manipulation, GemBox.Spreadsheet provides a high-level model that simplifies creating, modifying, and managing Excel files.

With GemBox.Spreadsheet .NET library, you can work with advanced Excel features such as charts, pivot tables, formulas, and more. In this guide, you will learn how to use it to create and manage Excel files in C# with just a few simple steps.

You can navigate through the following sections:

Installing the GemBox.Spreadsheet free version

Before you start, you need to install GemBox.Spreadsheet. The best way to do that is to install the NuGet Package by following these instructions:

Add the GemBox.Spreadsheet package using the following command from the NuGet Package Manager Console:

Install-Package GemBox.Spreadsheet

After installing the package, you must call the SpreadsheetInfo.SetLicense method before using any other member of the library.

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

In this tutorial, by using "FREE-LIMITED-KEY", you will be using GemBox's free mode. This mode allows you to use the library without purchasing a license, but with some limitations. If you purchased a license, you can replace "FREE-LIMITED-KEY" with your serial key.

You can check our step-by-step guide for more information on how to install and set up GemBox.Spreadsheet.

How to create an Excel file in C# and VB.NET

The code below shows how to create an Excel file programmatically and save it to XLSX format in C# and VB.NET.

// Create an Excel file.
var workbook = new ExcelFile();

// Add a new worksheet to the Excel file.
var worksheet = workbook.Worksheets.Add("New worksheet");

// Set the value of the cell "A1".
worksheet.Cells["A1"].Value = "Hello world!";

// Save the Excel file to a file format of your choice.
workbook.Save("Create.xlsx");
' Create an Excel file.
Dim workbook = New ExcelFile()

' Add a new worksheet to the Excel file.
Dim worksheet = workbook.Worksheets.Add("New worksheet")

' Set the value of the cell "A1".
worksheet.Cells("A1").Value = "Hello world!"

' Save the Excel file to a file format of your choice.
workbook.Save("Create.xlsx")

How to generate and format Excel files for reporting

Besides creating simple Excel files in C# and VB.NET, with GemBox.Spreadsheet you can also create custom reports using various Excel features supported by GemBox.Spreadsheet. Following is the list of steps that might help you to make your reports stand out, from adding text styles and colors to adjusting layouts and including headers and footers.

1. Adding and Formatting Text

When creating a well-structured report, it's often necessary to highlight key information with bold text, and you can do it in your worksheets as shown below:

// Set the value of the cell "A1".
worksheet.Cells["A1"].Value = "Some important information";

// Apply bold formatting to the cell
worksheet.Cells["A1"].Style.Font.Weight = ExcelFont.BoldWeight;
' Set the value of the cell "A1".
worksheet.Cells("A1").Value = "Some important information"

' Apply bold formatting to the cell
worksheet.Cells("A1").Style.Font.Weight = ExcelFont.BoldWeight

2. Applying Cell Colors

You can set the cell background color to improve readability and help distinguish sections of your report. For instance, you might want to color the top row to make it stand out from the data rows, as shown in the following code:

// Set the top row background color
worksheet.Rows[0].Style.FillPattern.SetSolid(
    SpreadsheetColor.FromName(ColorName.LightBlue));
' Set the top row background color
worksheet.Rows(0).Style.FillPattern.SetSolid(SpreadsheetColor.FromName(ColorName.LightBlue))

3. Setting Borders

Borders are essential for differentiating data sections in reports, especially when you need to present tables.

// Set the top row borders to thin black
worksheet.Rows[0].Style.Borders.SetBorders(
    MultipleBorders.All,
    SpreadsheetColor.FromName(ColorName.Black),
    LineStyle.Thin);
' Set the top row borders to thin black
worksheet.Rows(0).Style.Borders.SetBorders(MultipleBorders.All, SpreadsheetColor.FromName(ColorName.Black), LineStyle.Thin)

Discover more about cell formatting with our detailed example.

4. Adjusting Column Width

Automatically adjusting column width ensures that all content is visible and organized neatly. In most reports, columns with wider content, such as product names or descriptions, need extra space.

// Automatically adjust column width based on content
worksheet.Columns[0].AutoFit();
' Automatically adjust column width based on content
worksheet.Columns(0).AutoFit()

5. Adding Headers and Footers

Adding headers and footers provides context and professional details to reports, such as the company name, report title, or date.

// Add a header with report title and date
var header = worksheet.HeadersFooters.DefaultPage.Header;
header.CenterSection.Append("Report Title");
header.RightSection.Append(HeaderFooterFieldType.Date);

// Add a footer with page number
var footer = worksheet.HeadersFooters.DefaultPage.Footer;
footer.RightSection.Append(HeaderFooterFieldType.PageNumber);
' Add a header with report title and date
Dim header = worksheet.HeadersFooters.DefaultPage.Header
header.CenterSection.Append("Report Title")
header.RightSection.Append(HeaderFooterFieldType.Date)

' Add a footer with page number
Dim footer = worksheet.HeadersFooters.DefaultPage.Footer
footer.RightSection.Append(HeaderFooterFieldType.PageNumber)

Discover more about headers and footers with our detailed example.

6. Applying Conditional Formatting

Conditional formatting helps highlight specific data points, such as values above or below a certain threshold. This feature is valuable for identifying trends, outliers, and other key insights within large datasets.

// Add new worksheet for sales data
var dataSheet = workbook.Worksheets.Add("Data");

// Sample data
dataSheet.Cells["A1"].Value = "Month";
dataSheet.Cells["A2"].Value = "January";
dataSheet.Cells["A3"].Value = "February";
dataSheet.Cells["A4"].Value = "March";
dataSheet.Cells["A5"].Value = "April";
dataSheet.Cells["A6"].Value = "May";
dataSheet.Cells["A7"].Value = "June";
dataSheet.Cells["A8"].Value = "July";
dataSheet.Cells["A9"].Value = "August";
dataSheet.Cells["A10"].Value = "September";
dataSheet.Cells["A11"].Value = "October";
dataSheet.Cells["A12"].Value = "November";
dataSheet.Cells["A13"].Value = "December";

dataSheet.Cells["B1"].Value = "Sales";
dataSheet.Cells["B2"].Value = 5000;
dataSheet.Cells["B3"].Value = 7000;
dataSheet.Cells["B4"].Value = 8000;
dataSheet.Cells["B5"].Value = 4500;
dataSheet.Cells["B6"].Value = 3000;
dataSheet.Cells["B7"].Value = 9000;
dataSheet.Cells["B8"].Value = 5500;
dataSheet.Cells["B9"].Value = 6000;
dataSheet.Cells["B10"].Value = 9500;
dataSheet.Cells["B11"].Value = 8500;
dataSheet.Cells["B12"].Value = 4000;
dataSheet.Cells["B13"].Value = 5000;

// Apply conditional formatting to sales data
var condition = dataSheet.ConditionalFormatting.AddTopOrBottomRanked("B2:B13", false, 3);
condition.Style.FillPattern.PatternBackgroundColor = SpreadsheetColor.FromName(ColorName.LightGreen);
condition.Style.Font.Weight = ExcelFont.BoldWeight;
' Add new worksheet for sales data
Dim dataSheet = workbook.Worksheets.Add("Data")

' Sample data
dataSheet.Cells("A1").Value = "Month"
dataSheet.Cells("A2").Value = "January"
dataSheet.Cells("A3").Value = "February"
dataSheet.Cells("A4").Value = "March"
dataSheet.Cells("A5").Value = "April"
dataSheet.Cells("A6").Value = "May"
dataSheet.Cells("A7").Value = "June"
dataSheet.Cells("A8").Value = "July"
dataSheet.Cells("A9").Value = "August"
dataSheet.Cells("A10").Value = "September"
dataSheet.Cells("A11").Value = "October"
dataSheet.Cells("A12").Value = "November"
dataSheet.Cells("A13").Value = "December"

dataSheet.Cells("B1").Value = "Sales"
dataSheet.Cells("B2").Value = 5000
dataSheet.Cells("B3").Value = 7000
dataSheet.Cells("B4").Value = 8000
dataSheet.Cells("B5").Value = 4500
dataSheet.Cells("B6").Value = 3000
dataSheet.Cells("B7").Value = 9000
dataSheet.Cells("B8").Value = 5500
dataSheet.Cells("B9").Value = 6000
dataSheet.Cells("B10").Value = 9500
dataSheet.Cells("B11").Value = 8500
dataSheet.Cells("B12").Value = 4000
dataSheet.Cells("B13").Value = 5000

' Apply conditional formatting to sales data
Dim condition = dataSheet.ConditionalFormatting.AddTopOrBottomRanked("B2:B13", False, 3)
condition.Style.FillPattern.PatternBackgroundColor = SpreadsheetColor.FromName(ColorName.LightGreen)
condition.Style.Font.Weight = ExcelFont.BoldWeight

In this example, the top 3 sales values are highlighted in green, making it easy to identify the best-performing entries.

Discover more about conditional formatting with our detailed example.

7. Creating Charts

Charts are essential for visually summarizing and interpreting data. With GemBox.Spreadsheet, you can create different types of charts, such as bar, line, or pie charts, and customize their appearance.

The following code adds a column chart next to the data, summarizing monthly sales, which can be easily customized for different datasets or chart types.

// Create a column chart and select data for it.
var chart = dataSheet.Charts.Add(ChartType.Column, "D2", "M25");
chart.SelectData(dataSheet.Cells.GetSubrange("A1:B13"), true);
' Create a column chart and select data for it.
Dim chart = dataSheet.Charts.Add(ChartType.Column, "D2", "M25")
chart.SelectData(dataSheet.Cells.GetSubrange("A1:B13"), True)

Discover more about charts with our detailed example.

8. Building Pivot Tables

Pivot tables enable you to quickly summarize and analyze large datasets. In Excel, pivot tables are incredibly useful for creating flexible and interactive reports. The following code shows how to use GemBox.Spreadsheet to generate a pivot table.

// Create a new sheet for the pivot table.
var pivotSheet = workbook.Worksheets.Add("PivotTable");

// Specify header row.
pivotSheet.Cells["A1"].Value = "Product";
pivotSheet.Cells["B1"].Value = "Region";
pivotSheet.Cells["C1"].Value = "Sales";

// Insert random data to the sheet.
var random = new Random();
var products = new string[] { "Product A", "Product B", "Product C" };
var regions = new string[] { "North", "South", "East", "West", "Northeast" };
var rowIndex = 0;
foreach (var product in products)
    foreach (var region in regions)
    {
        rowIndex++;
        pivotSheet.Cells[rowIndex, 0].Value = product;
        pivotSheet.Cells[rowIndex, 1].Value = region;
        pivotSheet.Cells[rowIndex, 2].Value = random.Next(2000, 9800);
    }

// Create pivot cache from cell range "PivotTable!A1:C16".
var cache = workbook.PivotCaches.AddWorksheetSource("PivotTable!A1:C16");

// Create pivot table "Product Sales" using the specified pivot cache and add it to the worksheet at the cell location 'E1'.
var pivotTable = pivotSheet.PivotTables.Add(cache, "Product Sales", "E1");

// Aggregate 'Sales' values with sum.
var field = pivotTable.DataFields.Add("Sales");
field.Function = PivotFieldCalculationType.Sum;
field.Name = "Total Sales";
field.NumberFormat = "[$$-409]#,##0.00";

// Group rows into 'Products'.
pivotTable.RowFields.Add("Product");

// Group columns into 'Regions'.
pivotTable.ColumnFields.Add("Region");

// Specify the string to be displayed in row and column header.
pivotTable.RowHeaderCaption = "Products";
pivotTable.ColumnHeaderCaption = "Regions";
' Create a new sheet for the pivot table.
Dim pivotSheet = workbook.Worksheets.Add("PivotTable")

' Specify header row.
pivotSheet.Cells("A1").Value = "Product"
pivotSheet.Cells("B1").Value = "Region"
pivotSheet.Cells("C1").Value = "Sales"

' Insert random data to the sheet.
Dim random = New Random()
Dim products = New String() {"Product A", "Product B", "Product C"}
Dim regions = New String() {"North", "South", "East", "West", "Northeast"}
Dim rowIndex = 0

For Each product In products
	For Each region In regions
		rowIndex += 1
		pivotSheet.Cells(rowIndex, 0).Value = product
		pivotSheet.Cells(rowIndex, 1).Value = region
		pivotSheet.Cells(rowIndex, 2).Value = random.Next(2000, 9800)
	Next
Next

' Create pivot cache from cell range "PivotTable!A1:C16".
Dim cache = workbook.PivotCaches.AddWorksheetSource("PivotTable!A1:C16")

' Create pivot table "Product Sales" using the specified pivot cache and add it to the worksheet at the cell location 'E1'.
Dim pivotTable = pivotSheet.PivotTables.Add(cache, "Product Sales", "E1")

' Aggregate 'Sales' values with sum.
Dim field = pivotTable.DataFields.Add("Sales")
field.[Function] = PivotFieldCalculationType.Sum
field.Name = "Total Sales"
field.NumberFormat = "[$$-409]#,##0.00"

' Group rows into 'Products'.
pivotTable.RowFields.Add("Product")

' Group columns into 'Regions'.
pivotTable.ColumnFields.Add("Region")

' Specify the string to be displayed in row and column header.
pivotTable.RowHeaderCaption = "Products"
pivotTable.ColumnHeaderCaption = "Regions"

Discover more about pivot tables with our detailed example.

9. Adding Data Validation

With data validation, you can control the type of data entered in a cell, ensuring data accuracy and consistency. For instance, you may want to restrict user inputs to specific ranges or text formats, such as dates, numbers within a certain range, or specific values from a list.

// Create a new sheet for data validation.
var dataValidationSheet = workbook.Worksheets.Add("DataValidation");

// Add data validation for cell 'C2' to only accept values from 'B2:B5' range.
dataValidationSheet.Cells["B1"].Value = "List from B2 to B5 (on cell C2):";
dataValidationSheet.Cells["B2"].Value = "John";
dataValidationSheet.Cells["B3"].Value = "Fred";
dataValidationSheet.Cells["B4"].Value = "Hans";
dataValidationSheet.Cells["B5"].Value = "Ivan";
dataValidationSheet.DataValidations.Add(new DataValidation(worksheet, "C2")
{
    Type = DataValidationType.List,
    Formula1 = "=B2:B5",
    InputMessageTitle = "Enter a name",
    InputMessage = "Name must be from the list: John, Fred, Hans, Ivan.",
    ErrorStyle = DataValidationErrorStyle.Stop,
    ErrorTitle = "Invalid name",
    ErrorMessage = "Value must be a name from the list: John, Fred, Hans, Ivan."
});
' Create a new sheet for data validation.
Dim dataValidationSheet = workbook.Worksheets.Add("DataValidation")

' Add data validation for cell 'C2' to only accept values from 'B2:B5' range.
dataValidationSheet.Cells("B1").Value = "List from B2 to B5 (on cell C2):"
dataValidationSheet.Cells("B2").Value = "John"
dataValidationSheet.Cells("B3").Value = "Fred"
dataValidationSheet.Cells("B4").Value = "Hans"
dataValidationSheet.Cells("B5").Value = "Ivan"
dataValidationSheet.DataValidations.Add(New DataValidation(worksheet, "C2") With {
    .Type = DataValidationType.List,
    .Formula1 = "=B2:B5",
    .InputMessageTitle = "Enter a name",
    .InputMessage = "Name must be from the list: John, Fred, Hans, Ivan.",
    .ErrorStyle = DataValidationErrorStyle.[Stop],
    .ErrorTitle = "Invalid name",
    .ErrorMessage = "Value must be a name from the list: John, Fred, Hans, Ivan."
})

In this example, users are prompted to enter a name from a predefined list in the specified cell. If they enter an invalid value, an error message appears.

Discover more about data validation with our detailed example.

10. Saving the report

Once all formatting and features are in place, you can save your workbook as an Excel file. This report can now serve as an interactive tool, providing insights to end-users in a visually appealing format.

// Save report to file
workbook.Save("Report.xlsx");
' Save report to file
workbook.Save("Report.xlsx")

Supported file formats

Microsoft Excel supports many file formats suited for spreadsheets, from old legacy file formats to the newest XML-based file formats.

GemBox.Spreadsheet supports creating the following spreadsheet file formats using the same API: XLSX, XLS, XLSB, PDF, HTML, MHTML, ODS, CSV, TXT, XLSM, XLTX, XLTM, XPS, PNG, JPEG, GIF, BMP, TIFF, WMP, SVG.

To save the report to a specific format, all you have to do is specify the desired file extension when calling the Save (link) method. The following example shows how you can convert an XLSX file to any other supported file format in just one line of code:

// Convert the report to another format
workbook.Save("Report.%OutputFileType%");
' Convert the report to another format
workbook.Save("Report.%OutputFileType%")

Conclusion

GemBox.Spreadsheet simplifies the process of creating and managing Excel files in C#. With support for various formats and advanced features, it is an ideal solution for developers looking to work with Excel files without the need to use Office Interop or dealing with OpenXML complexities.

You can find the complete code of this article on Github.

See also


Next steps

GemBox.Spreadsheet is a .NET component that enables you to read, write, edit, convert, and print spreadsheet files from your .NET applications using one simple API.

Download Buy