How to Export To Excel Sheet & DOC format

appclass..................


namespace table
{
public class table1
{
public DataTable select()
{
SqlCommand cmd = new SqlCommand("select123", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adap = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adap.Fill(dt);
return dt;
}
}
}

//////////////////
code behind
........................

public partial class Export: System.Web.UI.Page
{
table.table1 db = new table.table1();
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dtOriginal = new DataTable();

dtOriginal = db.select();
DataTable dtTemp = new DataTable();

dtTemp.Columns.Add("ID");
dtTemp.Columns.Add("Employee Name");

String dtName;
DataRow drAddItem;
for (int i = 0; i < dtOriginal.Rows.Count; i++)
{
drAddItem = dtTemp.NewRow();
drAddItem[0] = dtOriginal.Rows[i][1].ToString();//ID

//Join Name

dtName = dtOriginal.Rows[i][2].ToString();
drAddItem[1] = dtName;


dtTemp.Rows.Add(drAddItem);
}

//Temp Grid
DataGrid dg = new DataGrid();
dg.DataSource = dtTemp;
dg.DataBind();
ExportToExcel("BudgeReport.xls", dg);
// ExportToExcel("BudgeReport.pdf", dg);

//ExportToExcel("BudgeReport.doc", dg);//for saving in doc format
dg = null;
dg.Dispose();

}

private void ExportToExcel(string strFileName, DataGrid dg)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
// Response.ContentType = "application/pdf";
//Response.ContentType = "application/doc";//for converting in doc format
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
dg.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
}


Related Articles

Export Data to Excel in CSV format using .NET

Export Data to excel in CSV format. .NET code to export CSV data. Free .NET code to export data to excel. .NET way of exporting data to excel. Explanation of .NET code to export data to excel in CSV.

More articles: Export to Excel

Comments

Author: Kapil Dhawan18 Jun 2008 Member Level: Gold   Points : 2

Hello
Nice piece of code
Thanks for sharing your knowledge with us.
I hope to see more good code from your side
This code will help lots of guys
Thanks to you
Regards,
Kapil

Author: Shivshanker Cheral18 Jun 2008 Member Level: Gold   Points : 0

Thanks for sharing



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: