Thursday, March 31, 2011

Import data from sqlserver into Excel Sheet Using DataTable


static DataTable dta;
SqlDataAdapter da = new SqlDataAdapter("select * from Emp", conn);
  DataSet    ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
         
            dta = ds.Tables[0];
     
        }

        string attachment = "attachment; filename=Address.xls";

        Response.ClearContent();

        Response.AddHeader("content-disposition", attachment);

        Response.ContentType = "application/vnd.ms-excel";

        string tab = "";

        foreach (DataColumn dc in dta.Columns)
        {

            Response.Write(tab + dc.ColumnName);

            tab = "\t";

        }

        Response.Write("\n");



        int i;

        foreach (DataRow dr in dta.Rows)
        {

            tab = "";

            for (i = 0; i < dta.Columns.Count; i++)
            {

                Response.Write(tab + dr[i].ToString());

                tab = "\t";

            }

            Response.Write("\n");

        }

        Response.End();

0 comments:

Post a Comment