DataGrid格式化输出到Excel表

来源:互联网 发布:js点击加载更多 编辑:程序博客网 时间:2024/05/16 01:52

以前用ASP的时候,也使用过输出到EXCEL或者WORD的方法;

并且在些次开发.NET项目中也照搬ASP的方法过来,特别是在输出一些数据统计和备份的时候,使用输出到EXCEL更加明了,排版也更加清晰…… 但很快,我就发现一个问题,比如说:“我在给一个游戏帐号充值的时候,此帐号名称为0开头的帐号,这样的结果输出到Excel的时候,前面的0你会发现不见了”,这就是没有格式化输出的原因

 //以下这段代码是放到Page_Load()里面

Response.Clear();
                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();

 

以下代码(就是格式化输出各项字段)(不要忘了事件的映射):

        private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        
{
            
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中显示出来。按所要求的格式排好版
查阅起来更加直观...