今天弄了一下控件导出Excel,于是产生了格式问题了,一些日期如20091222的名称被显示为科学记数法。
所以,我搜了博客园。一大堆的文章都是复制来复制去的资料。
基本上都有这么一行闪亮的代码:文本:vnd.ms-excel.numberformat:@
有深入一点的文章,会告诉你,这个东西要写在<td style="vnd.ms-excel.numberformat:@">xxx</td>里
于是这里就产生这两个分支方法:
1.直接就写上<td style="vnd.ms-excel.numberformat:@"><%# Eval("XXX") %></td>
2.没法直接写<td的,由GridView等直接产生Table的就来后台循环输出法:
这里随便拿一段:
//对需要格式化的列进行格式化
//e.Item.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
--------------------------------------------------------------------------------------
实际上,我们导出Excel后,如果用记事本打开,可以发现,实际差不多就是个html。
即然是html,当然也可以用样式了。既然不能引用外部样式,那直接就写内部样式就行了。
于是,我产生了这么一小段代码:
代码
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding( " gb2312 " );
HttpContext.Current.Response.Write( " <meta http-equiv=Content-Type content=text/html;charset=gb2312> " );
HttpContext.Current.Response.AppendHeader( " content-disposition " , " attachment;filename=export.xls " );
HttpContext.Current.Response.ContentType = " application/vnd.ms-excel " ;
StringBuilder sb = new StringBuilder();
sb.Append( " <head><style>table td,th{vnd.ms-excel.numberformat:@;text-align: center;} table th{color:red}</style></head> " ); // 关键看这里,格式化,并为标题加红色
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding( " gb2312 " );
HttpContext.Current.Response.Write( " <meta http-equiv=Content-Type content=text/html;charset=gb2312> " );
HttpContext.Current.Response.AppendHeader( " content-disposition " , " attachment;filename=export.xls " );
HttpContext.Current.Response.ContentType = " application/vnd.ms-excel " ;
StringBuilder sb = new StringBuilder();
sb.Append( " <head><style>table td,th{vnd.ms-excel.numberformat:@;text-align: center;} table th{color:red}</style></head> " ); // 关键看这里,格式化,并为标题加红色
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
foreach (Control ct in ctList)
{
ct.RenderControl(htw);
}
sb.Append(sw.ToString());
sw.Close();
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.End( );
HtmlTextWriter htw = new HtmlTextWriter(sw);
foreach (Control ct in ctList)
{
ct.RenderControl(htw);
}
sb.Append(sw.ToString());
sw.Close();
HttpContext.Current.Response.Write(sb.ToString());
HttpContext.Current.Response.End( );
至此,通过在输出前,附加<style></style>样式,即可控件Excel的输出格式了。