Export Datatable to Excel in asp.net


public void ExportToExcel(DataTable dt, string name, HttpResponse res)

    {
        string attachment = "attachment; filename=" + name;


        res.ClearContent();
        res.AddHeader("content-disposition", attachment);
        res.ContentType = "application/vnd.ms-excel";
        string tab = "";
        int colcount = 0;
        foreach (DataColumn din in dt.Columns)
        {

            // Response.Write(tab + dc.ColumnName.Remove(0, dc.ColumnName.IndexOf("-") + 1));
            res.Write(tab + din.ColumnName);
            tab = "\t";
            colcount++;
        }
        res.Write("\n");

        int i;
        foreach (DataRow dr in dt.Rows)
        {
            tab = "";
            for (i = 0; i < dt.Columns.Count; i++)
            {
                res.Write(tab + dr[i].ToString());
                tab = "\t";
            }
            res.Write("\n");
        }
        res.End();
    }



4 comments:

  1. Can you give an example on how this would be called?

    ReplyDelete
  2. You should call this method by passing your dataset table[0] and name of your data as parameters.
    This method is useful when you export Gridview data to Excel by pass Gridview datasource dataset table[0] as a parameter.

    ReplyDelete
  3. Data from datatable can be imported into excel file with Aspose.Cells for .NET Library also. You can find sample code for this here.

    ReplyDelete