Thursday, March 12, 2009

Export to excel, word in .net

Hi,

Here is the code to export the grid data to excel or word:

// create an enum
public enum ExportType
{

EXCEL,

PDF,

WORD
}

//source can be DataSet, DataTable and etc
public void ExportDataGrid(object source, ExportType type)
{
try
{
// setting temporarily datagrid
DataGrid dg = new DataGrid();
dg.ID = "GridView1";
dg.DataSource = source;
dg.AutoGenerateColumns = true;
dg.AllowPaging = false;
dg.AllowSorting = false;
dg.DataBind();
// export selected format
Response.Clear();
Response.Buffer = true;
switch ((type))
{
case ExportType.EXCEL:
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "ExportedGridData"));
break;
case ExportType.PDF:
break;
// TODO
case ExportType.WORD:
Response.ContentType = "application/ms-word";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.doc", "ExportedGridData"));
break;
}
Response.Charset = "";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
dg.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
catch (Exception ex)
{
if ((ex.Message != "Thread was being aborted."))
{
Response.Write(("Error occur while exporting excel. For more information:" + ex.Message));
}
}
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];

if (ds.Tables[0].Rows.Count > 0)
{
ExportDataGrid(ds, ExportType.EXCEL);
}
}
protected void btnExportToWord_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];

if (ds.Tables[0].Rows.Count > 0)
{
ExportDataGrid(ds, ExportType.WORD);
}
}

protected void btnExportToPDF_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = (DataSet)Session["ds"];

if (ds.Tables[0].Rows.Count > 0)
{
ExportDataGrid(ds, ExportType.PDF);
}
}

No comments:

Post a Comment