datagrid导出excle及行列的属性设置

导出EXCLE  

 Response.Clear();
    Response.ClearHeaders();
    Response.BufferOutput = false;
    Response.ContentType = "application/ms-excel";  
    Response.AppendHeader("Content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("AppointmentOrders_" + ddl_MCList.SelectedItem.Text + "_" +  DateTime.Parse(startTime.Value).ToString("yyyyMMdd") + ".xls", System.Text.Encoding.UTF8));
    this.EnableViewState = false;
    System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
    DataGrid1.RenderControl(oHtmlTextWriter);
    Response.Write(oStringWriter.ToString());
    Response.End();

属性设置

protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
       
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            e.Item.Cells[
0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            e.Item.Cells[
3].Attributes.Add("style", "vnd.ms-excel.numberformat:¥#,###.00");
        }
    }
 

关健是这两句啦

e.Item.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");//格式字符串比如080001没有这句话就会变成80001
            e.Item.Cells[
3].Attributes.Add("style", "vnd.ms-excel.numberformat:¥#,###.00");

 

还有其它

       首先,我们了解一下excel从web页面上导出的原理。当我们把这些数据发送到客户端时,我们想让客户端程序(浏览器)以excel的格式读取它,所以把mime类型设为:application/vnd.ms-excel,当excel读取文件时会以每个cell的格式呈现数据,如果cell没有规定的格式,则excel会以默认的格式去呈现该cell的数据。这样就给我们提供了自定义数据格式的空间,当然我们必须使用excel支持的格式。下面就列出常用的一些格式:
1) 文本:vnd.ms-excel.numberformat:@
2) 日期:vnd.ms-excel.numberformat:yyyy/mm/dd
3) 数字:vnd.ms-excel.numberformat:#,##0.00
4) 货币:vnd.ms-excel.numberformat:¥#,##0.00
5) 百分比:vnd.ms-excel.numberformat: #0.00%
posted on 2011-06-16 13:22  AlvinXiao  阅读(580)  评论(0编辑  收藏  举报