Hi indradeo,
Using the article i have created the example.
Refer below code.
HTML
<asp:Button Text="Export" OnClick="ExportExcel" runat="server" />
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using ClosedXML.Excel;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Diagnostics
Imports System.IO
Imports ClosedXML.Excel
Code
C#
protected void ExportExcel(object sender, EventArgs e)
{
string filePath = Server.MapPath("~/SqlExport.xlsx");
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt, "Customers");
using (MemoryStream ms = new MemoryStream())
{
wb.SaveAs(ms);
File.WriteAllBytes(filePath, ms.ToArray());
}
}
}
}
}
}
if (File.Exists(filePath))
{
Process.Start(filePath);
}
}
VB.Net
Protected Sub ExportExcel(ByVal sender As Object, ByVal e As EventArgs)
Dim filePath As String = Server.MapPath("~/SqlExport.xlsx")
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Customers")
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As DataTable = New DataTable()
sda.Fill(dt)
Using wb As XLWorkbook = New XLWorkbook()
wb.Worksheets.Add(dt, "Customers")
Using ms As MemoryStream = New MemoryStream()
wb.SaveAs(ms)
File.WriteAllBytes(filePath, ms.ToArray())
End Using
End Using
End Using
End Using
End Using
End Using
If File.Exists(filePath) Then
Process.Start(filePath)
End If
End Sub