Hi gkoutsiv,
Check this example. Now please take its reference and correct your code.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download the database table SQL by clicking the download link below.
Download SQL file
HTML
<asp:Button Text="Export" OnClick="ExportExcel" runat="server" />
Namespaces
C#
using System.IO;
using System.Data;
using ClosedXML.Excel;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.IO
Imports System.Data
Imports ClosedXML.Excel
Imports System.Configuration
Imports System.Data.SqlClient
Code
C#
protected void ExportExcel(object sender, EventArgs e)
{
if (!Directory.Exists(Server.MapPath("~/Files")))
{
Directory.CreateDirectory(Server.MapPath("~/Files"));
}
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");
wb.SaveAs(Server.MapPath("~/Files/SqlExport.xlsx"));
}
}
}
}
}
}
VB.Net
Protected Sub ExportExcel(sender As Object, e As EventArgs)
If Not Directory.Exists(Server.MapPath("~/Files")) Then
Directory.CreateDirectory(Server.MapPath("~/Files"))
End If
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT * FROM Customers")
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
Using wb As New XLWorkbook()
wb.Worksheets.Add(dt, "Customers")
wb.SaveAs(Server.MapPath("~/Files/SqlExport.xlsx"))
End Using
End Using
End Using
End Using
End Using
End Sub
Exported Excel