当前位置:编程学习 > C#/ASP.NET >>

asp.net导出数据到excel方法

 代码如下 复制代码

public static void TableToExcel(System.Data.DataTable dt, string fileType)
  {
  System.IO.StringWriter sw = new System.IO.StringWriter();
  System.Text.StringBuilder sb = new System.Text.StringBuilder();
  if (fileType.Equals("xls"))
  {
  foreach (System.Data.DataColumn col in dt.Columns)
  {
  sb.Append(col.ColumnName + "t");
  }
  sw.WriteLine(sb.ToString());
  }

  foreach (System.Data.DataRow row in dt.Rows)
  {
  sb = new System.Text.StringBuilder();
  foreach (System.Data.DataColumn col in dt.Columns)
  {
  sb.Append(row[col.ColumnName].ToString().Replace(Environment.NewLine, " ").Replace("t", "") + "t");
  }
  sw.WriteLine(sb.ToString());
  }
  sw.Close();
  string fileName = (dt.TableName ?? "data") + (fileType.Equals("xls") ? ".xls" : ".txt");
  System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
  response.Clear();
  response.Buffer = true;
  response.Charset = "gb2312";
  response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
  response.ContentType = fileType.Equals("xls") ? "application/ms-excel" : "text/plain";
  response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
  response.Write(sw);
  response.End();
  }

补充:asp.net教程,.Net开发
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,