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);
}
}
}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



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.









