This way
HTML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="Customer Id" ItemStyle-Width="80" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="120" />
</Columns>
</asp:GridView>
<br />
<asp:Button Text="Export" OnClick="ExportExcel" runat="server" />
Namespaces
using System.IO;
using System.Data;
using ClosedXML.Excel;
using System.Net.Mail;
using System.Configuration;
using System.Data.SqlClient;
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
GridView1.DataSource = this.GetData();
GridView1.DataBind();
}
}
private DataTable GetData()
{
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);
return dt;
}
}
}
}
}
protected void ExportExcel(object sender, EventArgs e)
{
//Get the GridView Data from database.
DataTable dt = GetData();
//Set DataTable Name which will be the name of Excel Sheet.
dt.TableName = "GridView_Data";
//Create a New Workbook.
using (XLWorkbook wb = new XLWorkbook())
{
//Add the DataTable as Excel Worksheet.
wb.Worksheets.Add(dt);
using (MemoryStream memoryStream = new MemoryStream())
{
//Save the Excel Workbook to MemoryStream.
wb.SaveAs(memoryStream);
//Convert MemoryStream to Byte array.
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
//Send Email with Excel attachment.
using (MailMessage mm = new MailMessage("sender@gmail.com", "recipient@gmail.com"))
{
mm.Subject = "GridView Exported Excel";
mm.Body = "GridView Exported Excel Attachment";
//Add Byte array as Attachment.
mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "GridView.xlsx"));
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
credentials.UserName = "sender@gmail.com";
credentials.Password = "<password>";
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
smtp.Send(mm);
}
}
}
}
Screenshot