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();
}
|