Thursday, 13 September 2012

Export to DataTable To Excel Using Asp.Net

Here Your ds contain the DataTable to which you want to export in excel-sheet format
  if (ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                {
                    string attachment = "attachment; filename=PenaltyRiskReport.xls";
                    HttpContext context = HttpContext.Current;

                    context.Response.Clear();

                    foreach (DataColumn column in dt.Columns)
                        context.Response.Write(column.ColumnName + "\t");

                    context.Response.Write(Environment.NewLine);

                    foreach (DataRow row in dt.Rows)
                    {
                        for (int i = 0; i < dt.Columns.Count; i++)
                            context.Response.Write(row[i].ToString() + "\t");
                        context.Response.Write(Environment.NewLine);
                    }

                    context.Response.ContentType = "text/vnd.ms-excel";
                    context.Response.AppendHeader("Content-Disposition", attachment);
                    context.Response.End();
                }
                else
                {
                    lblMessage.Text = "No Records Found";
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                }

            }
            else
            {
                lblMessage.Text = "No Records Found";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }

2 comments:

  1. thank you very much

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete