using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using ClosedXML.Excel;
namespace JqueryTutorial
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
GetData();
}
}
private void GetData()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)), new DataColumn("Name", typeof(string)), new DataColumn("Country", typeof(string)) });
dt.Rows.Add(1, "abc", "UK");
dt.Rows.Add(2, "def", "India");
dt.Rows.Add(3, "ghi", "France");
dt.Rows.Add(4, "jkl", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnExport_Click(object sender, EventArgs e)
{
GridView1.AllowSorting = false;
GridView1.AllowPaging = false;
this.GetData();
EnableViewState = false;
Response.Clear();
DataTable dt2 = new DataTable("GridView1");
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
dt2.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView1.Rows)
{
dt2.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
if (!string.IsNullOrEmpty(row.Cells[i].Text))
{
dt2.Rows[dt2.Rows.Count - 1][i] = row.Cells[i].Text;
}
else
{
List<control> controls = new List<control>();
foreach (Control control in row.Cells[i].Controls)
{
controls.Add(control);
}
foreach (Control control in controls)
{
switch (control.GetType().Name)
{
case "Label":
string label = (control as Label).Text;
dt2.Rows[dt2.Rows.Count - 1][i] = label;
break;
case "TextBox":
string textbox = (control as TextBox).Text;
dt2.Rows[dt2.Rows.Count - 1][i] = textbox;
break;
case "HyperLink":
string hyperLink = (control as HyperLink).Text;
dt2.Rows[dt2.Rows.Count - 1][i] = hyperLink;
break;
case "LinkButton":
string linkButton = (control as LinkButton).Text;
dt2.Rows[dt2.Rows.Count - 1][i] = linkButton;
break;
case "CheckBox":
string checkBox = (control as CheckBox).Text;
dt2.Rows[dt2.Rows.Count - 1][i] = checkBox;
break;
case "RadioButton":
string radioButton = (control as RadioButton).Text;
dt2.Rows[dt2.Rows.Count - 1][i] = radioButton;
break;
}
row.Cells[i].Controls.Remove(control);
}
}
}
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt2);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GridView.xls");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
}
}