[导入]asp.net 把datatable的数据导出到EXCEL

网上找到一段把dataset中的datatable的数据导出到excel,先把代码记下来先,试过之后会把实际效果帖上

程序代码
protected void Page_Load(object sender, EventArgs e)
{
       SqlConnection cn = new SqlConnection("yourconnectionstring");
       cn.Open();
       SqlDataAdapter da = new SqlDataAdapter("Select * FROM Users", cn);
       DataTable dt = new DataTable();
       da.Fill(dt);
       cn.Close();

       Response.Clear();
       Response.ContentType = "application/vnd.ms-excel";
       string sep = "";
       foreach (DataColumn dc in dt.Columns)
       {
              Response.Write(sep + dc.ColumnName);
              sep = "\t";
       }
       Response.Write("\n");

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

}



文章来源: http://blog.nwtbb.cn/default.asp?id=345

你可能感兴趣的:(Datatable)