Skip to footer content
USING IRONXL

Export DataGridView to Excel in C# with IronXL

Export DataGridView data to Excel in C# using IronXL, which eliminates Microsoft Office dependencies and provides container-friendly deployment. Create a WorkBook, iterate through DataGridView cells, and save to XLSX format with full formatting support.

Exporting data from a Windows Forms DataGridView to Excel is a common requirement in business applications. Whether generating reports, creating data backups, or sharing information with stakeholders, developers need a reliable way to export GridView data to Excel format. Traditional approaches using Microsoft Office Interop have served this purpose, but they come with deployment complexities and dependency requirements that can complicate application distribution.

This tutorial demonstrates a practical C# example for exporting DataGridView data to Excel using IronXL, a .NET library that eliminates the need for Microsoft Office installation. You will explore how to implement a clean, efficient export solution that works across different environments, including cloud platforms and containers. Whether deploying to Azure or running applications in Docker containers, IronXL provides the deployment flexibility that DevOps teams require.

IronXL homepage showcasing C# code example for reading Excel files without Microsoft Office or Excel Interop, featuring syntax highlighting and NuGet download statistics.

Why Is DataGridView to Excel Export Essential?

DataGridView controls are fundamental to Windows Forms applications, displaying tabular data that users interact with daily. Exporting this data to Excel enables users to apply Excel's powerful analysis tools, create presentations, and share data with colleagues who may not have access to the application. This C# Excel export functionality is crucial for business reporting and data analysis workflows.

Traditional export methods using Microsoft.Office.Interop.Excel require Excel to be installed on every machine running the application. This creates deployment challenges, especially in server environments or when distributing applications to users without Office licenses. Additionally, Interop approaches can suffer from memory leaks and COM object cleanup issues if not handled carefully. These challenges become particularly acute when deploying to AWS Lambda or other serverless platforms where Office installation is not feasible.

Modern .NET applications demand more flexible solutions. IronXL addresses these challenges by providing a standalone library that generates Excel files without any Microsoft Office dependencies. This approach ensures consistent functionality across development, testing, and production environments while supporting deployment to containers and cloud platforms.

Cross-platform support diagram showing .NET compatibility across multiple versions (9, 8, 7, 6, Core, Standard, Framework) with icons for various platforms including Windows, Linux, Mac, Docker, Azure, and AWS.

How Do IronXL and Interop Compare?

The table below summarizes the key differences between IronXL and Microsoft Office Interop for Excel export scenarios:

IronXL vs. Microsoft Office Interop for Excel Export
Feature IronXL Microsoft Interop
Office installation required No Yes
Linux / Docker support Yes No
COM object cleanup Not required Manual, error-prone
Memory leak risk Low High if not disposed
Cloud / serverless deployment Supported Not supported
Export formats (XLSX, CSV, JSON, XML) All supported Limited

How Do You Install IronXL in Your C# Project?

Open the Package Manager Console in Visual Studio and run the following command, or use the .NET CLI:

Install-Package IronXL
dotnet add package IronXL
Install-Package IronXL
dotnet add package IronXL
SHELL

Terminal output showing successful installation of IronXL.Excel NuGet package and its dependencies in a C# project

For detailed installation options, refer to the IronXL NuGet installation guide or search for the package directly on NuGet.org. Once installed, add using IronXL; to your C# project files to access the library's Excel export capabilities. When deploying to production environments, apply your license key to enable all features. You can get a free trial license to evaluate IronXL before purchasing.

What Does a Basic DataGridView Export Look Like?

The code below creates a sample Windows Forms application with a DataGridView populated with data, then exports it to Excel using IronXL top-level statements:

using IronXL;
using System.Data;
using System.Windows.Forms;

// Create a DataTable with sample product data
var dt = new DataTable();
dt.Columns.Add("Product ID", typeof(int));
dt.Columns.Add("Product Name", typeof(string));
dt.Columns.Add("Category", typeof(string));
dt.Columns.Add("Price", typeof(decimal));
dt.Columns.Add("Stock", typeof(int));

dt.Rows.Add(1001, "Laptop Pro", "Electronics", 1299.99m, 15);
dt.Rows.Add(1002, "Wireless Mouse", "Accessories", 29.99m, 50);
dt.Rows.Add(1003, "USB-C Cable", "Accessories", 19.99m, 100);
dt.Rows.Add(1004, "Monitor 27\"", "Electronics", 399.99m, 8);
dt.Rows.Add(1005, "Keyboard Mechanical", "Accessories", 89.99m, 25);

// Bind to DataGridView
var dataGridView1 = new DataGridView();
dataGridView1.DataSource = dt;

// Create new Excel workbook
var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
var worksheet = workbook.DefaultWorkSheet;

// Export column headers
for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
{
    worksheet.SetCellValue(0, colIndex, dataGridView1.Columns[colIndex].HeaderText);
}

// Export data rows
for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count; rowIndex++)
{
    if (!dataGridView1.Rows[rowIndex].IsNewRow)
    {
        for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
        {
            var cellValue = dataGridView1.Rows[rowIndex].Cells[colIndex].Value;
            if (cellValue is decimal or double or int)
                worksheet.SetCellValue(rowIndex + 1, colIndex, Convert.ToDouble(cellValue));
            else
                worksheet.SetCellValue(rowIndex + 1, colIndex, cellValue?.ToString() ?? string.Empty);
        }
    }
}

// Save the Excel file
workbook.SaveAs("DataGridViewExport.xlsx");
Console.WriteLine("Export completed successfully!");
using IronXL;
using System.Data;
using System.Windows.Forms;

// Create a DataTable with sample product data
var dt = new DataTable();
dt.Columns.Add("Product ID", typeof(int));
dt.Columns.Add("Product Name", typeof(string));
dt.Columns.Add("Category", typeof(string));
dt.Columns.Add("Price", typeof(decimal));
dt.Columns.Add("Stock", typeof(int));

dt.Rows.Add(1001, "Laptop Pro", "Electronics", 1299.99m, 15);
dt.Rows.Add(1002, "Wireless Mouse", "Accessories", 29.99m, 50);
dt.Rows.Add(1003, "USB-C Cable", "Accessories", 19.99m, 100);
dt.Rows.Add(1004, "Monitor 27\"", "Electronics", 399.99m, 8);
dt.Rows.Add(1005, "Keyboard Mechanical", "Accessories", 89.99m, 25);

// Bind to DataGridView
var dataGridView1 = new DataGridView();
dataGridView1.DataSource = dt;

// Create new Excel workbook
var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
var worksheet = workbook.DefaultWorkSheet;

// Export column headers
for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
{
    worksheet.SetCellValue(0, colIndex, dataGridView1.Columns[colIndex].HeaderText);
}

// Export data rows
for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count; rowIndex++)
{
    if (!dataGridView1.Rows[rowIndex].IsNewRow)
    {
        for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
        {
            var cellValue = dataGridView1.Rows[rowIndex].Cells[colIndex].Value;
            if (cellValue is decimal or double or int)
                worksheet.SetCellValue(rowIndex + 1, colIndex, Convert.ToDouble(cellValue));
            else
                worksheet.SetCellValue(rowIndex + 1, colIndex, cellValue?.ToString() ?? string.Empty);
        }
    }
}

// Save the Excel file
workbook.SaveAs("DataGridViewExport.xlsx");
Console.WriteLine("Export completed successfully!");
$vbLabelText   $csharpLabel

This code demonstrates the core export functionality. The DataTable setup populates the grid with sample product data, which serves as a common data source for DataGridView controls. When working with larger datasets, consider using IronXL's DataSet import and export capabilities for improved performance.

The export loop iterates through the DataGridView to place both headers and data into Excel cells using SetCellValue with row and column indices. The IronXL documentation covers additional cell write options for more complex scenarios. The IsNewRow check skips the empty row at the bottom of editable DataGridViews, ensuring clean Excel output without unexpected blank rows.

Windows Forms application showing a DataGridView populated with product data including Product ID, Name, Category, Price, and Stock columns, with an 'Export to Excel' button below.

Microsoft Excel spreadsheet showing exported product data with columns for Product ID, Product Name, Category, Price, and Stock levels for electronics and computer accessories.

If you are implementing this feature in a web-based ASP.NET MVC application, extend the approach by returning the file as a downloadable response using the Content-Disposition HTTP header. For ASP.NET WebForms developers, you may need to override VerifyRenderingInServerForm when exporting controls to ensure proper rendering. Visit the IronXL features page for a complete list of supported scenarios.

How Do You Add Professional Formatting to Excel Exports?

Professional Excel exports often require formatting to improve readability. IronXL provides styling capabilities including font customization, background colors, borders, and alignment. The example below adds header formatting and alternating row colors:

using IronXL;
using System.Data;
using System.Windows.Forms;

// Assume dataGridView1 is already populated with data
var dataGridView1 = new DataGridView();

// (populate dataGridView1 with data as shown in the previous example)

var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
var worksheet = workbook.DefaultWorkSheet;

// Set column headers with formatting
for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
{
    var headerCell = worksheet.GetCellAt(0, colIndex);
    headerCell.Value = dataGridView1.Columns[colIndex].HeaderText;
    headerCell.Style.Font.Bold = true;
    headerCell.Style.BackgroundColor = "#4472C4";
    headerCell.Style.Font.Color = "#FFFFFF";
    headerCell.Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
}

// Export data with alternating row colors
for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count; rowIndex++)
{
    if (!dataGridView1.Rows[rowIndex].IsNewRow)
    {
        for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
        {
            var cellValue = dataGridView1.Rows[rowIndex].Cells[colIndex].Value;
            var excelCell = worksheet.GetCellAt(rowIndex + 1, colIndex);

            if (cellValue != null)
                excelCell.Value = cellValue.ToString();

            // Apply alternating row background
            if (rowIndex % 2 == 0)
                excelCell.Style.BackgroundColor = "#F2F2F2";
        }
    }
}

// Auto-fit columns
for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
{
    worksheet.AutoSizeColumn(colIndex);
}

workbook.SaveAs("FormattedExport.xlsx");
Console.WriteLine("Formatted export completed successfully!");
using IronXL;
using System.Data;
using System.Windows.Forms;

// Assume dataGridView1 is already populated with data
var dataGridView1 = new DataGridView();

// (populate dataGridView1 with data as shown in the previous example)

var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
var worksheet = workbook.DefaultWorkSheet;

// Set column headers with formatting
for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
{
    var headerCell = worksheet.GetCellAt(0, colIndex);
    headerCell.Value = dataGridView1.Columns[colIndex].HeaderText;
    headerCell.Style.Font.Bold = true;
    headerCell.Style.BackgroundColor = "#4472C4";
    headerCell.Style.Font.Color = "#FFFFFF";
    headerCell.Style.HorizontalAlignment = IronXL.Styles.HorizontalAlignment.Center;
}

// Export data with alternating row colors
for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count; rowIndex++)
{
    if (!dataGridView1.Rows[rowIndex].IsNewRow)
    {
        for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
        {
            var cellValue = dataGridView1.Rows[rowIndex].Cells[colIndex].Value;
            var excelCell = worksheet.GetCellAt(rowIndex + 1, colIndex);

            if (cellValue != null)
                excelCell.Value = cellValue.ToString();

            // Apply alternating row background
            if (rowIndex % 2 == 0)
                excelCell.Style.BackgroundColor = "#F2F2F2";
        }
    }
}

// Auto-fit columns
for (int colIndex = 0; colIndex < dataGridView1.Columns.Count; colIndex++)
{
    worksheet.AutoSizeColumn(colIndex);
}

workbook.SaveAs("FormattedExport.xlsx");
Console.WriteLine("Formatted export completed successfully!");
$vbLabelText   $csharpLabel

This enhanced version applies professional formatting to the exported Excel file. Headers receive bold text with a blue background and white font color, creating a clear visual distinction from data rows. The code implements alternating row colors using a modulo operation, improving readability for large datasets. You can further customize the appearance using the IronXL cell formatting guide or apply merge cells functionality to span header columns.

The AutoSizeColumn method adjusts column widths to fit content, eliminating manual adjustment after export. These formatting options transform a basic data export into a presentation-ready document that users can share immediately. Review how to write Excel files with IronXL for more formatting and data writing patterns.

How Do You Export to Multiple Formats and Add Formulas?

IronXL extends beyond basic Excel export, offering features such as formula support, multiple worksheets, and alternative output formats. The following example demonstrates these capabilities:

using IronXL;

var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
var worksheet = workbook.DefaultWorkSheet;

// (populate worksheet with DataGridView data as shown above)
int dataRowCount = 5; // Replace with actual dataGridView1.Rows.Count

// Add a SUM formula to calculate the total price column
worksheet.SetCellValue(dataRowCount + 2, 3, $"=SUM(D2:D{dataRowCount + 1})");

// Create a summary worksheet
var summarySheet = workbook.CreateWorkSheet("Summary");
summarySheet.SetCellValue(0, 0, "Total Products");
summarySheet.SetCellValue(0, 1, dataRowCount);

// Save in multiple formats
workbook.SaveAs("export.xlsx");
workbook.SaveAsCsv("export.csv");
workbook.SaveAsJson("export.json");
workbook.SaveAsXml("export.xml");

Console.WriteLine("Multi-format export completed!");
using IronXL;

var workbook = WorkBook.Create(ExcelFileFormat.XLSX);
var worksheet = workbook.DefaultWorkSheet;

// (populate worksheet with DataGridView data as shown above)
int dataRowCount = 5; // Replace with actual dataGridView1.Rows.Count

// Add a SUM formula to calculate the total price column
worksheet.SetCellValue(dataRowCount + 2, 3, $"=SUM(D2:D{dataRowCount + 1})");

// Create a summary worksheet
var summarySheet = workbook.CreateWorkSheet("Summary");
summarySheet.SetCellValue(0, 0, "Total Products");
summarySheet.SetCellValue(0, 1, dataRowCount);

// Save in multiple formats
workbook.SaveAs("export.xlsx");
workbook.SaveAsCsv("export.csv");
workbook.SaveAsJson("export.json");
workbook.SaveAsXml("export.xml");

Console.WriteLine("Multi-format export completed!");
$vbLabelText   $csharpLabel

IronXL supports Excel formulas, allowing you to add calculations directly to exported files. The example above adds a SUM formula to calculate column totals automatically. Creating multiple worksheets helps organize complex exports, such as separating detailed data from summary information. Visit the IronXL how-to guide for creating Excel files for more worksheet management patterns.

The format flexibility is particularly valuable for integration scenarios. While XLSX is the standard for Excel files, CSV export provides universal compatibility with database systems and older applications. JSON and XML formats facilitate data exchange with web services and APIs. You can also open existing workbooks to append exported data to existing spreadsheets rather than creating new files each time.

How Do Different Export Formats Compare?

Excel spreadsheet showing a product inventory with columns for Product ID, Name, Category, Price, and Stock, with a sum formula result of 1839.95 displayed in cell D9.

Excel spreadsheet showing a 'Summary' worksheet with 'Total Products: 5' in cells A1 and B1, demonstrating the result of exporting DataGridView data to Excel with multiple worksheets.

Excel spreadsheet showing product inventory data with columns for ProductID, Product Name, Category, Price, and Stock quantities, with a sum of 1839.95 displayed in cell D9.

JSON file showing product data with fields for Product ID, Name, Category, Price, and Stock in a code editor interface.

XML file showing exported DataGridView data with product information including IDs, names, categories, prices, and stock levels organized in Sheet elements.

How Does IronXL Simplify Your C# Development Workflow?

IronXL's primary advantage is eliminating Microsoft Office dependencies. Your application runs consistently whether deployed on a developer workstation, a customer machine, or a Docker container. This independence simplifies deployment and reduces support issues related to Office versions and installations. The Open XML SDK from Microsoft is another Office-free alternative, though it requires significantly more boilerplate code compared to IronXL's higher-level API. For cross-platform .NET 10 development guidance, the Microsoft .NET documentation covers platform targets, deployment models, and Windows Forms specifics.

The library's API design prioritizes simplicity. Unlike Interop's COM-based approach that requires careful object disposal, IronXL uses standard .NET patterns that feel natural to C# developers. Cross-platform support means export functionality built for Windows Forms can be reused in ASP.NET Core applications running on Linux servers. For a full overview of available capabilities, visit the IronXL features page.

You can also import data from Excel to pre-populate your DataGridView before exporting, creating round-trip workflows where users load Excel data, edit it in the grid, and export the result back to Excel. The read Excel file guide covers the import side in detail.

When working with sensitive data, IronXL supports workbook-level and worksheet-level password protection. The IronXL documentation covers security options for scenarios where exported files must be protected before distribution.

Feature overview of an Excel library showing six main categories: Create, Save and Export, Edit Workbooks, Working With Data, Secure Your Workbooks, and Edit Layout options.

What Are the Licensing Options for Production Use?

IronXL requires a valid license key for production deployments. You can start with a free trial license that unlocks all features for evaluation. Review the IronXL licensing page for full details on available tiers, from single-developer licenses to unlimited enterprise deployments.

Apply the license key in your application before using any IronXL functionality:

IronXL.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
IronXL.License.LicenseKey = "YOUR-LICENSE-KEY-HERE";
$vbLabelText   $csharpLabel

This single line activates the library for the lifetime of the application process. For web applications and services, set the license key during startup so all requests benefit from the full feature set without watermarks.

IronXL licensing options showing four tiers: Lite ($749), Plus ($999), Professional ($1,999), and Unlimited ($3,999) with varying developer, location, and project limits

Why Should You Choose IronXL for Excel Exports in C#?

Exporting DataGridView data to Excel becomes straightforward with IronXL. The library eliminates traditional Interop complexities while providing professional formatting capabilities and multiple export formats. Its container-friendly architecture, minimal dependencies, and cross-platform support make it ideal for modern DevOps workflows.

The IronXL home page is the starting point for exploring the full library. Whether building microservices, deploying to Kubernetes clusters, or running serverless functions, IronXL integrates cleanly into CI/CD pipelines. The export Excel how-to guide provides additional patterns for different export scenarios, and the open workbook guide covers reading and modifying existing files.

Start with a free trial license to explore the full feature set. IronXL tutorials and code examples help you implement production-ready solutions quickly. Choose from flexible licensing options that suit your deployment needs, from individual developer licenses to unlimited enterprise deployments. For any questions about getting started, the IronXL documentation hub provides API references, code samples, and troubleshooting guidance.

Frequently Asked Questions

What is the benefit of using IronXL for exporting DataGridView to Excel?

IronXL simplifies the process of exporting DataGridView contents to Excel by eliminating the need for Microsoft Office Interop, reducing deployment complexities, and removing dependency requirements.

How does IronXL improve application distribution?

IronXL reduces application distribution complexities by not requiring Microsoft Office Interop, which often comes with additional dependencies that can complicate deployment.

Can IronXL export DataGridView data in VB.NET?

Yes, IronXL provides a practical solution for exporting DataGridView data to Excel in VB.NET, making it easier to manage data in business applications.

What are common use cases for exporting DataGridView to Excel?

Common use cases include generating reports, creating data backups, and sharing information with stakeholders in a business context.

Does IronXL require Microsoft Excel to be installed on the system?

No, IronXL does not require Microsoft Excel to be installed, as it operates independently of Excel, simplifying the deployment process.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me