Last updated: 31st October 2026
Exporting data from an ASP.NET application to Microsoft Excel is a useful feature when users need to download, analyze, or share information stored in a database.In this tutorial, I'll show you how to export records from a SQL Server database to an Excel worksheet using Microsoft Office Interop in ASP.NET. The examples use both C# and VB.NET.
We'll also see how to format the Excel worksheet automatically, add a title, display column headings, and download the generated Excel file through the browser.
I have recently added a feature to Download the Excel file after exporting the data.
👉 Please note that this tutorial and its examples are still relevant and it works fine.

What is Microsoft Office Interop?
C#
using Excel = Microsoft.Office.Interop.Excel;
VB
Imports Excel = Microsoft.Office.Interop.Excel
Microsoft Office Interop provides a way to interact with Microsoft Office applications programmatically. Using the Microsoft.Office.Interop.Excel namespace, a .NET application can create workbooks, add worksheets, enter data, format cells, and save Excel files.
Note: Office Interop is intended primarily for desktop automation. Although it can work in certain configured Windows environments, Microsoft does not recommend unattended server-side Office automation in ASP.NET or IIS applications. For production web applications, consider a library such as ClosedXML or the Open XML SDK.
Let's begin with the example.
Create a new website and add few controls on your web page. I'll keep this example short and simple. We need a button to export the data and two more buttons to view or donwload the excel file, once we have exported the data to excel.
But, first we'll create an SQL Server table.
Create a SQL Server table
For this example, I'll use an Employee Details table containing "employee name", "address", "mobile numbers", and "email address". Here's sample Employee Details table.
<!DOCTYPE html>
<html>
<head>
<title>Export Data to Excel in ASP.NET</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<!-- BUTTON CONTROL TO EXPORT DATA TO EXCEL. -->
<p><input type="button" onserverclick="ExportToExcel"
value="Export data to Excel" runat="server" /></p>
<!-- SHOW MESSAGE. -->
<p><asp:Label ID="lblConfirm" Text="" runat="server"></asp:Label></p>
<div>
<!-- VIEW BUTTON WILL OPEN THE EXCEL FILE FOR VIEWING. -->
<div>
<input type="button" onserverclick="ViewData"
id="btView" value="View Data" runat="server"
style="display:none" />
</div>
<!--DOWNLOAD EXCEL FILE. -->
<div style="float:left;">
<asp:Button ID="btDownLoadFile" Text="Download"
OnClick="DownLoadFile"
runat="server" style="display:none" />
</div>
</div>
</div>
</form>
</body>
</html>Add the Microsoft Excel Interop reference
In Visual Studio, add a reference to the Microsoft Excel Object Library.
Add a COM reference: "Microsoft Excel 12.0 Object Library"
using System; using System.Data; using System.Data.SqlClient; using System.IO; using Excel = Microsoft.Office.Interop.Excel; using ExcelAutoFormat = Microsoft.Office.Interop.Excel.XlRangeAutoFormat; public partial class _Default : System.Web.UI.Page { protected void ExportToExcel(object sender, EventArgs e) { // Set the connection string string sCon = "Data Source=DNA;Persist Security Info=False;Integrated Security=SSPI;" + "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;"; // Connect to SQL Server using (SqlConnection con = new SqlConnection(sCon)) { // Fetch employee records using (SqlCommand cmd = new SqlCommand("SELECT *FROM dbo.EmployeeDetails")) { SqlDataAdapter sda = new SqlDataAdapter(); try { cmd.Connection = con; con.Open(); sda.SelectCommand = cmd; // Store data in DataTable DataTable dt = new DataTable(); sda.Fill(dt); if (dt.Rows.Count > 0) { string path = Server.MapPath("exportedfiles\\"); // Check if folder exists. If no folder found, create a new export folder. if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // Delete the file before creating a new one. File.Delete(path + "EmployeeDetails.xlsx"); // Create Excel workbook Excel.Application xlAppToExport = new Excel.Application(); xlAppToExport.Workbooks.Add(""); // Add a worksheet Excel.Worksheet xlWorkSheetToExport = default(Excel.Worksheet); xlWorkSheetToExport = (Excel.Worksheet)xlAppToExport.Sheets["Sheet1"]; // Row from where the data starts showing. int iRowCnt = 4; // Show the header xlWorkSheetToExport.Cells[1, 1] = "Employee Details"; Excel.Range range = xlWorkSheetToExport.Cells[1, 1] as Excel.Range; range.EntireRow.Font.Name = "Calibri"; range.EntireRow.Font.Bold = true; range.EntireRow.Font.Size = 20; // Merge cells of the header xlWorkSheetToExport.Range["A1:D1"].MergeCells = true; // Show columns on the top xlWorkSheetToExport.Cells[iRowCnt - 1, 1] = "Employee Name"; xlWorkSheetToExport.Cells[iRowCnt - 1, 2] = "Mobile No."; xlWorkSheetToExport.Cells[iRowCnt - 1, 3] = "PresentAddress"; xlWorkSheetToExport.Cells[iRowCnt - 1, 4] = "Email Address"; // Insert database records into Excel int i; for (i = 0; i <= dt.Rows.Count - 1; i++) { xlWorkSheetToExport.Cells[iRowCnt, 1] = dt.Rows[i].Field<string>("EmpName"); xlWorkSheetToExport.Cells[iRowCnt, 2] = dt.Rows[i].Field<string>("Mobile"); xlWorkSheetToExport.Cells[iRowCnt, 3] = dt.Rows[i].Field<string>("PresentAddress"); xlWorkSheetToExport.Cells[iRowCnt, 4] = dt.Rows[i].Field<string>("Email"); iRowCnt = iRowCnt + 1; } // Apply Excel formatting using AUTOFORMAT function Excel.Range range1 = xlAppToExport.ActiveCell.Worksheet.Cells[4, 1] as Excel.Range; range1.AutoFormat(ExcelAutoFormat.xlRangeAutoFormatList3); // SAVE Excel file in the folder. xlWorkSheetToExport.SaveAs(path + "EmployeeDetails.xlsx"); // Clear. xlAppToExport.Workbooks.Close(); xlAppToExport.Quit(); xlAppToExport = null; xlWorkSheetToExport = null; lblConfirm.Text = "Data Exported Successfully"; lblConfirm.Attributes.Add("style", "color:green; font: normal 14px Verdana;"); btView.Attributes.Add("style", "display:block"); btDownLoadFile.Attributes.Add("style", "display:block"); } } catch (Exception ex) { lblConfirm.Text = ex.Message.ToString(); lblConfirm.Attributes.Add("style", "color:red; font: bold 14px/16px Sans-Serif,Arial"); } finally { sda.Dispose(); sda = null; } } } } // VIEW THE EXPORTED EXCEL DATA. protected void ViewData(object sender, System.EventArgs e) { string path = Server.MapPath("exportedfiles\\"); try { // CHECK IF THE FOLDER EXISTS. if (Directory.Exists(path)) { // CHECK IF THE FILE EXISTS. if (File.Exists(path + "EmployeeDetails.xlsx")) { // SHOW (NOT DOWNLOAD) THE EXCEL FILE. Excel.Application xlAppToView = new Excel.Application(); xlAppToView.Workbooks.Open(path + "EmployeeDetails.xlsx"); xlAppToView.Visible = true; } } } catch (Exception ex) { // } } // DOWNLOAD THE FILE. protected void DownLoadFile(object sender, EventArgs e) { try { string sPath = Server.MapPath("exportedfiles\\"); Response.AppendHeader("Content-Disposition", "attachment; filename=EmployeeDetails.xlsx"); Response.TransmitFile(sPath + "EmployeeDetails.xlsx"); Response.End(); } catch (Exception ex) { } } }
Option Explicit On Imports System.Data ' FOR "DataTable" Imports System.Data.SqlClient Imports System.IO ' FOR FILE ACCESS. Imports Excel = Microsoft.Office.Interop.Excel Imports ExcelAutoFormat = Microsoft.Office.Interop.Excel.XlRangeAutoFormat Partial Class _Default Inherits System.Web.UI.Page Protected Sub btExport_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles btExport.ServerClick ' SET THE CONNECTION STRING. Dim sCon As String = "Data Source=dna;Persist Security Info=False;Integrated Security=SSPI;" & _ "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=demo;Connect Timeout=30;" Using con As SqlConnection = New SqlConnection(sCon) Using cmd As SqlCommand = New SqlCommand("SELECT *FROM dbo.EmployeeDetails") Dim sda As SqlDataAdapter = New SqlDataAdapter Try cmd.Connection = con : con.Open() sda.SelectCommand = cmd Dim dt As DataTable = New DataTable sda.Fill(dt) If dt.Rows.Count > 0 Then Dim path As String = Server.MapPath("exportedfiles\") ' CHECK IF THE FOLDER EXISTS. IF NOT, CREATE A NEW FOLDER. If Not Directory.Exists(path) Then Directory.CreateDirectory(path) End If File.Delete(path & "EmployeeDetails.xlsx") ' DELETE THE FILE BEFORE CREATING A NEW ONE. ' ADD A WORKBOOK USING THE EXCEL APPLICATION. Dim xlAppToExport As New Excel.Application xlAppToExport.Workbooks.Add() ' ADD A WORKSHEET. Dim xlWorkSheetToExport As Excel.Worksheet xlWorkSheetToExport = xlAppToExport.Sheets("Sheet1") ' ROW ID FROM WHERE THE DATA STARTS SHOWING. Dim iRowCnt As Integer = 4 With xlWorkSheetToExport ' SHOW THE HEADER. .Cells(1, 1).value = "Employee Details" .Cells(1, 1).FONT.NAME = "Calibri" .Cells(1, 1).Font.Bold = True .Cells(1, 1).Font.Size = 20 .Range("A1:D1").MergeCells = True ' MERGE CELLS OF THE HEADER. ' SHOW COLUMNS ON THE TOP. .Cells(iRowCnt - 1, 1).value = "Employee Name" .Cells(iRowCnt - 1, 2).value = "Mobile No." .Cells(iRowCnt - 1, 3).value = "PresentAddress" .Cells(iRowCnt - 1, 4).value = "Email Address" For i = 0 To dt.Rows.Count - 1 .Cells(iRowCnt, 1).value = dt.Rows(i).Item("EmpName") .Cells(iRowCnt, 2).value = dt.Rows(i).Item("Mobile") .Cells(iRowCnt, 3).value = dt.Rows(i).Item("PresentAddress") .Cells(iRowCnt, 4).value = dt.Rows(i).Item("Email") iRowCnt = iRowCnt + 1 Next ' FINALLY, FORMAT THE EXCEL SHEET USING EXCEL'S AUTOFORMAT FUNCTION. xlAppToExport.ActiveCell.Worksheet.Cells(4, 1).AutoFormat( _ ExcelAutoFormat.xlRangeAutoFormatList3) End With ' SAVE THE FILE IN A FOLDER. xlWorkSheetToExport.SaveAs(path & "EmployeeDetails.xlsx") ' CLEAR. xlAppToExport.Workbooks.Close() : xlAppToExport.Quit() xlAppToExport = Nothing : xlWorkSheetToExport = Nothing lblConfirm.Text = "Data Exported Sucessfully" lblConfirm.Attributes.Add("style", "color:green; font: normal 14px Verdana;") btView.Attributes.Add("style", "display:block") btDownLoadFile.Attributes.Add("style", "display:block") End If Catch ex As Exception lblConfirm.Text = ex.Message lblConfirm.Attributes.Add("style", "color:red; font: bold 14px/16px Sans-Serif,Arial") Finally sda.Dispose() : sda = Nothing End Try End Using End Using End Sub ' VIEW THE EXPORTED EXCEL DATA. Protected Sub btView_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles btView.ServerClick Dim path As String = Server.MapPath("exportedfiles\") Try If Directory.Exists(path) Then ' CHECK IF THE FOLDER EXISTS. If File.Exists(path & "EmployeeDetails.xlsx") Then ' CHECK IF THE FILE EXISTS. ' SHOW (NOT DOWNLOAD) THE EXCEL FILE. Dim xlAppToView As New Excel.Application xlAppToView.Workbooks.Open(path & "EmployeeDetails.xlsx") xlAppToView.Visible = True End If End If Catch ex As Exception ' End Try End Sub ' DOWNLOAD THE FILE. Protected Sub DownLoadFile(ByVal sender As Object, ByVal e As EventArgs) Try Dim sPath As String = Server.MapPath("exportedfiles\") Response.AppendHeader("Content-Disposition", "attachment;filename=EmployeeDetails.xlsx") Response.TransmitFile(sPath & "EmployeeDetails.xlsx") Response.[End]() Catch ex As Exception End Try End Sub End Class
Now, you can also export data from Paging enabled GridView to Excel in ASP.NET. Check out this article.
