Skip to footer content
USING IRONXL

Export GridView to Excel with Formatting C# Using IronXL

Exporting GridView Data to Excel with Formatting Using C#

Exporting GridView data to Excel while preserving cell colors, fonts, and formatting is a common challenge in ASP.NET web development, especially for applications targeting a global audience (en-US). The export GridView to Excel with formatting C# process is handled on the server, which manages data binding, rendering, and output formatting. Traditional methods using new HtmlTextWriter and new StringWriter to write control output often produce Excel files with format warnings. Some developers figured out a workaround using public override void VerifyRenderingInServerForm; you must add the VerifyRenderingInServerForm event to avoid runtime errors during the export process. However, this approach creates HTML-based files that MS Excel may not render correctly. The GridView must be placed inside a form tag with runat="server" to successfully export to Excel. By default, certain export options or settings may apply unless explicitly changed, such as the ExportAll option or maximum rows. In both C# and VB.NET implementations, export logic is commonly triggered from a button click event, where the event handler signature includes parameters such as object sender, EventArgs e in C# or ByVal sender As Object, ByVal e As EventArgs in VB.NET.

IronXL provides a cleaner solution—creating native Excel files with full formatting control, no Microsoft Office installation required. This article demonstrates how to export GridView to Excel in both ASP.NET Web Forms and Windows Forms applications.

Introduction to Exporting Data

Exporting data from a GridView to an Excel file is a fundamental feature in many ASP.NET and Windows Forms applications. Whether you are building a reporting dashboard or providing users with the ability to download data for offline analysis, the ability to export GridView content to an Excel sheet ensures your data is accessible and easy to work with in MS Excel. This process typically involves transferring the values from the GridView control—such as rows, columns, and cells—into a structured Excel file, while maintaining the desired formatting and style.

A well-designed export to Excel solution goes beyond simply copying data; it also preserves string styles, applies alternating row color for readability, and sets up the correct content disposition so users can download the file as an attachment. Developers often use code samples that demonstrate how to create an Excel file programmatically, leveraging methods like public override void VerifyRenderingInServerForm to avoid runtime errors in ASP.NET, and Response.AddHeader to specify the filename and attachment type. In Windows Forms, the export process is similar, but the file is saved directly to the system rather than streamed to the browser.

Formatting is a key aspect of a professional export. By customizing the font, background color, and borders, you can ensure the exported Excel sheet matches your application’s look and feel. Using objects like new StringWriter and new HtmlTextWriter, or more advanced libraries, you can control the output and structure of your Excel file. Error handling is also essential—by catching exceptions (such as Exception ex), you can provide a smooth user experience even if something goes wrong during the export process.

How to Export Windows Forms DataGridView to Excel File with Cell Formatting Using object sender

The most reliable method extracts the GridView’s underlying DataTable and builds a styled Excel sheet programmatically. This approach avoids format errors and gives complete control over header styles, alternating row color, and borders. Note that if your page uses paging, disable it before export to capture all records.

Windows Forms applications use DataGridView control instead of web-based GridView. The export to Excel process follows the same pattern—extract cell values from rows and cells collections, then apply formatting.

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

private void btnExport_Click(object sender, EventArgs e)
{
    DataTable dt = (DataTable)GridView1.DataSource;
    WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet workSheet = workBook.DefaultWorkSheet;
    // Export header row with formatting
    for (int col = 0; col < dt.Columns.Count; col++)
    {
        workSheet.SetCellValue(0, col, dt.Columns[col].ColumnName);
        var cell = workSheet.GetCellAt(0, col);
        cell.Style.Font.Bold = true;
        cell.Style.SetBackgroundColor("#4472C4");
        cell.Style.Font.Color = "#FFFFFF";
        cell.Style.BottomBorder.Type = BorderType.Thin;
    }
    // Export data rows with alternating row color
    for (int row = 0; row < dt.Rows.Count; row++)
    {
        for (int col = 0; col < dt.Columns.Count; col++)
        {
            var cellValue = dt.Rows[row][col];
            workSheet.SetCellValue(row + 1, col, cellValue?.ToString() ?? "");
            var cell = workSheet.GetCellAt(row + 1, col);
            string bgColor = (row % 2 == 0) ? "#D6DCE5" : "#FFFFFF";
            cell.Style.SetBackgroundColor(bgColor);
            cell.Style.BottomBorder.Type = BorderType.Thin;
        }
    }
    // Save and write response for download
    MemoryStream stream = workBook.ToStream();
    using (SaveFileDialog saveFileDialog = new SaveFileDialog())
    {
        saveFileDialog.Filter = "Excel Files|*.xlsx";
        saveFileDialog.Title = "Save Excel File";
        saveFileDialog.FileName = "GridViewExport.xlsx";
        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            using (FileStream fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
            {
                stream.WriteTo(fileStream);
            }
            MessageBox.Show("Export successful.", "Export", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
using IronXL;
using IronXL.Styles;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

private void btnExport_Click(object sender, EventArgs e)
{
    DataTable dt = (DataTable)GridView1.DataSource;
    WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
    WorkSheet workSheet = workBook.DefaultWorkSheet;
    // Export header row with formatting
    for (int col = 0; col < dt.Columns.Count; col++)
    {
        workSheet.SetCellValue(0, col, dt.Columns[col].ColumnName);
        var cell = workSheet.GetCellAt(0, col);
        cell.Style.Font.Bold = true;
        cell.Style.SetBackgroundColor("#4472C4");
        cell.Style.Font.Color = "#FFFFFF";
        cell.Style.BottomBorder.Type = BorderType.Thin;
    }
    // Export data rows with alternating row color
    for (int row = 0; row < dt.Rows.Count; row++)
    {
        for (int col = 0; col < dt.Columns.Count; col++)
        {
            var cellValue = dt.Rows[row][col];
            workSheet.SetCellValue(row + 1, col, cellValue?.ToString() ?? "");
            var cell = workSheet.GetCellAt(row + 1, col);
            string bgColor = (row % 2 == 0) ? "#D6DCE5" : "#FFFFFF";
            cell.Style.SetBackgroundColor(bgColor);
            cell.Style.BottomBorder.Type = BorderType.Thin;
        }
    }
    // Save and write response for download
    MemoryStream stream = workBook.ToStream();
    using (SaveFileDialog saveFileDialog = new SaveFileDialog())
    {
        saveFileDialog.Filter = "Excel Files|*.xlsx";
        saveFileDialog.Title = "Save Excel File";
        saveFileDialog.FileName = "GridViewExport.xlsx";
        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            using (FileStream fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write))
            {
                stream.WriteTo(fileStream);
            }
            MessageBox.Show("Export successful.", "Export", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
$vbLabelText   $csharpLabel

This example creates a button click handler with object sender and EventArgs e parameters. The code casts the GridView’s DataSource property to a DataTable, providing access to all values in your data table. The WorkBook.Create method initializes a new Excel file, and DefaultWorkSheet returns the active worksheet. You can specify the sheet name through the SheetName property during export.

The DataGridView export accesses column headers through the HeaderText property. Cell values come from the Cells collection using row and column indices. The var keyword with null-conditional operator handles empty cells by converting null to an empty string. Unlike ASP.NET that uses Response to write the file for web download, Windows Forms saves directly to the system. IronXL creates native XLSX or XLS format files that open in MS Excel without format warnings.

Output

Export GridView to Excel with Formatting C# Using IronXL: Image 1 - GridView Output

Export GridView to Excel with Formatting C# Using IronXL: Image 2 - Excel Output

Export GridView to Excel with Formatting C# Using IronXL: Image 3 - Message Output

Conclusion

IronXL transforms GridView export to Excel from a formatting challenge into a straightforward process. The library handles header styling, alternating row color, conditional formatting, and borders—without Office dependencies. We hope this tutorial helps you create professional Excel exports in your .NET applications.

Start your free trial to export GridView data with formatting, or explore licensing options for deployment. For support and details, refer to the documentation.

Frequently Asked Questions

How can I export GridView data to Excel in C#?

You can export GridView data to Excel in C# by using the IronXL library. It allows you to programmatically create Excel files and export data with ease, including formatting and styles.

Why should I use IronXL for exporting GridView data?

IronXL simplifies the process of exporting GridView data with its intuitive API, allowing you to maintain formatting and apply styles effortlessly, which can be challenging with traditional methods.

Does IronXL support formatting when exporting GridView to Excel?

Yes, IronXL supports various formatting options, including fonts, colors, and cell styles, ensuring that your exported Excel files look professional and maintain the intended design.

Can I customize the appearance of Excel files generated from GridView data?

IronXL provides a range of customization options for Excel files, allowing you to adjust cell styles, fonts, colors, and more to match your specific requirements when exporting from GridView.

Is it possible to export large GridView datasets to Excel using IronXL?

IronXL is capable of handling large datasets efficiently, ensuring that you can export extensive GridView data to Excel without performance issues.

What are the benefits of exporting GridView data to Excel using IronXL over other methods?

IronXL offers a more streamlined and flexible approach to exporting GridView data, providing robust support for formatting, customization, and handling large datasets, making it superior to many other methods.

How do I maintain data integrity when exporting GridView to Excel?

IronXL ensures data integrity by accurately converting and preserving data types and formats during the export process from GridView to Excel.

Can IronXL export data from GridView controls with complex structures?

Yes, IronXL can effectively handle and export data from GridView controls with complex structures, maintaining the hierarchy and formatting in the resulting Excel file.

What file formats can IronXL export GridView data to?

IronXL primarily exports data to Excel formats such as XLSX, but it also supports other formats like CSV, enabling flexibility depending on your needs.

Is there support for exporting GridView with conditional formatting using IronXL?

IronXL supports conditional formatting, allowing you to set rules and styles that dynamically adjust based on cell values when exporting GridView data to Excel.

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