以前用ASP的時候,也使用過輸出到EXCEL或者WORD的方法;
並且在些次開發.NET項目中也照搬ASP的方法過來,特別是在輸出一些數據統計和備份的時候,使用輸出到EXCEL更加明瞭,排版也更加清晰…… 但很快,我就發現一個問題,比如說:“我在給一個遊戲帳號充值的時候,此帳號名稱爲0開頭的帳號,這樣的結果輸出到Excel的時候,前面的0你會發現不見了”,這就是沒有格式化輸出的原因
//以下這段代碼是放到Page_Load()裏面
Response.Charset="GB2312";
string filename="ReChargeReport"+Convert.ToDateTime(Request.QueryString["s"]).ToString("yyyy-MM");
Response.AddHeader("Content-Disposition", "attachment; filename="+filename+".xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//設置輸出流爲簡體中文
Response.ContentType="application/vnd.ms-excel";
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN",true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.DataGrid1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
以下代碼(就是格式化輸出各項字段)(不要忘了事件的映射):
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Cells[0].Attributes.Add("style","vnd.ms-excel.numberformat:0");
e.Item.Cells[1].Attributes.Add("style","vnd.ms-excel.numberformat:@");
e.Item.Cells[2].Attributes.Add("style","vnd.ms-excel.numberformat:@");
e.Item.Cells[3].Attributes.Add("style","vnd.ms-excel.numberformat:yyyy年mm月dd日-hh:mm:ss");
e.Item.Cells[4].Attributes.Add("style","vnd.ms-excel.numberformat:@");
e.Item.Cells[5].Attributes.Add("style","vnd.ms-excel.numberformat:¥#,###.00");
e.Item.Cells[6].Attributes.Add("style","vnd.ms-excel.numberformat:0");
}
}
這樣做只有一個目的,使輸出的信息格式化...並能夠完整地在Excel中顯示出來。按所要求的格式排好版
查閱起來更加直觀...