ASP.NET GridView控件匯出EXCEL-設置單元格數值型樣式
时间:2011-02-21 来源:yellowwood
一、要點
1,CSS樣式
2,RenderControl() 方法
二、Number CSS 樣式
mso-number-format:"0" (NO Decimals )
mso-number-format:"0\.000" (3 Decimals )
mso-number-format:"\#\,\#\#0\.000" (Comma with 3 dec )
mso-number-format:"mm\/dd\/yy" (Date7 )
mso-number-format:"mmmm\ d\,\ yyyy" (Date9 )
mso-number-format:"m\/d\/yy\ h\:mm\ AM\/PM" (D -T AMPM )
mso-number-format:"Short Date" (01/03/1998 )
mso-number-format:"Medium Date" (01-mar-98 )
mso-number-format:"d\-mmm\-yyyy" (01-mar-1998 )
mso-number-format:"Short Time" (5:16 )
mso-number-format:"Medium Time" (5:16 am )
mso-number-format:"Long Time" (5:16:21:00 )
mso-number-format:"Percent" (Percent - two decimals )
mso-number-format:"0%" (Percent - no decimals )
mso-number-format:"0\.E+00" (Scientific Notation )
mso-number-format:"\@" (Text )
mso-number-format:"\#\ ???\/???" (Fractions - up to 3 digits (312/943) )
mso-number-format:"\0022£\0022\#\,\#\#0\.00" (£12.76 )
mso-number-format:"\#\,\#\#0\.00_ \;\[Red\]\-\#\,\#\#0\.00\ " 2 decimals, negative numbers in red and signed
(1.56 -1.56)
三、使用CSS樣式匯出EXCEL
例如,數值設置為文本格式。
public static void gridviewDownloadExcel(ref HttpResponse response, ref GridView grid, string FileName)
{
// Excel 單元格數值型樣式
string style = @"<style>.text {mso-number-format:\@;}</script>";
response.Clear();
// 文件編碼、類型
response.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName + ".xls");
response.ContentType = "application/vnd.ms-excel";
StringWriter writer = new StringWriter();
HtmlTextWriter htmlwriter = new HtmlTextWriter(writer);
// 控件的內容轉為text/html
grid.RenderControl(htmlwriter);
// 添加樣式
response.Write(style);
// 輸出
response.Write(writer.ToString());
response.End();
}