最近將自己在項目中經常用到的excel導出方法分析如下,如有不妥之處望他人指出,如果有更好的方法希望展示出來互相學習。
//導出事件
PRotected void btnexcel_Click(object sender, EventArgs e)
{
//定義導出Excel的標題
List<string> tabletitle = new List<string>(); tabletitle.Add("企業注冊號"); tabletitle.Add("企業名稱"); tabletitle.Add("企業開業日期");
DataTable dt=GetCompanyList();
Print(dt, tabletitle);
}
/// <summary> /// 輸出Excel /// </summary> /// <param name="dt">數據</param> /// <param name="title">表頭</param> public static void Print(DataTable dt, List<String> title) { StringBuilder sHtml = new StringBuilder(); sHtml.Append("<meta http-equiv='content-type' content='application/ms-excel; charset=UTF-8'/>"); sHtml.Append("<table border=1>"); sHtml.Append("<tr style='background-color:#D8DFF1;'>"); foreach (String s in title) { sHtml.Append("<td>"); sHtml.Append(s); sHtml.Append("</td>"); } sHtml.Append("</tr>"); foreach (DataRow row in dt.Rows) { sHtml.Append("<td style=/"vnd.ms-excel.numberformat:@/">"); //注:style=/"vnd.ms-excel.numberformat:@/" 去除科學計數法表示方式,以文本方式顯示。 sHtml.Append(row["zch"].ToString()); sHtml.Append("</td>"); sHtml.Append("<td>"); sHtml.Append(row["qymc"].ToString()); sHtml.Append("</td>"); sHtml.Append("<td>"); sHtml.Append(row["kyrq"] != null && row["kyrq"].ToString() != "" ? Convert.ToDateTime(row["kyrq"]).ToString("yyyy-MM-dd") : ""); sHtml.Append("</td>"); sHtml.Append("</tr>"); } sHtml.Append("</table>");
System.Web.HttpContext.Current.Response.Charset = "GB2312"; System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode( DateTime.Now.ToString("yyyyMMddhhmmsss") + ".xls", System.Text.Encoding.UTF8).ToString()); System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel"; System.Web.HttpContext.Current.Response.Output.Write(sHtml); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End();
}
新聞熱點
疑難解答