之前在导出Excel的时候,总是会以科学记数法显示较大数字,甚至一些字符比如"10500E000054"也会被认为是数字而以科学记数法的方式显示,很是麻烦,网上搜索不少资料,终于解决,记录如下:
第一种方法导出Excel,会产生科学记数法的问题:
public void CreateExcel(DataTable dt, IList<KeyValuePair<string, string>> head, string FileType, string FileName) { Response.Clear(); Response.Charset = "UTF-8"; Response.Buffer = true; Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\""); Response.ContentType = FileType; string colHeaders = string.Empty; StringWriter sw = new StringWriter(); foreach (KeyValuePair<string, string > k in head) { if (dt.Columns.Contains(k.Key)) { sw.Write(k.Value + "\t"); } } sw.Write(sw.NewLine); string ls_item = string.Empty; int cl = dt.Columns.Count; foreach (DataRow row in dt.Rows) { foreach (KeyValuePair<string, string > k in head) { if (dt.Columns.Contains(k.Key)) { sw.Write(row[k.Key].ToString() + "\t"); } } sw.Write(sw.NewLine); } Response.OutPut.Flush(); Response.Write(sw); Response.End(); } |
这种方法会保留Excel原生的网络线。
第二种方法,解决科学记数法的问题:
public void CreateExcel(DataTable dt, IList<KeyValuePair<string, string>> head, string FileType, string FileName) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Charset = "UTF-8"; HttpContext.Current.Response.ContentType = "Application/vnd.ms-xls"; HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"); StringBuilder table = new StringBuilder(); table.Append("<table border=1 ><tr >"); foreach (KeyValuePair<string, string > k in head) { if (dt.Columns.Contains(k.Key)) { table.Append("<td style='font-weight:bold' >");//标题加粗显示 table.Append(k.Value); //表格的标题 table.Append("</td >"); } } table.Append("</tr >"); foreach (DataRow row in dt.Rows) { table.Append("<tr >"); foreach (KeyValuePair<string, string > k in head) { if (dt.Columns.Contains(k.Key)) { table.Append("<td style='vnd.ms-excel.numberformat:@' >"); table.Append(row[k.Key].ToString()); table.Append("</td >"); } } table.Append("</tr >"); } table.Append("</table >"); HttpContext.Current.Response.Write(table); HttpContext.Current.Response.End(); } |
这种方法解决了科学记数法的问题,但默认会不显示网格线,用户可能会不喜欢,所以我在table.Append("<table border=1 ><tr >");中加了border=1模拟网格线,效果还不错。
本人喜欢第二种方法,主要可以使用css来控制导出的样式,非常方便。
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理