GridView to Excel (add style)

GridView to Excel (add style)

網路上也很多DataGrid to execel的分享, 請自行找G大神


        Response.Cache.SetExpires(DateTime.Now.AddSeconds(1));
        Response.ContentType = "application/vnd.ms-excel";
        Response.Charset = "";
        this.EnableViewState = false;
        Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">\r\n");
        
        Response.Write(style); // add style

        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        this.GridView1.RenderControl(hw);
        Response.AppendHeader("content-disposition", "attachment;filename=customer_information.xls");
        byte[] b = StringToBytes(tw.ToString());
        Response.OutputStream.Write(b, 0, b.Length);// 用Response.Write(s:string)時, always is utf-8 encoding. (excel 2003 can't 正常顯示 utf-8's 中文)

        Response.End();
    }

1. excel's free style 有時會造成使用者的困擾.

如: 手機是number 但最前方的0會被trim掉.

如: 數字過大時會變成 exponential number表示法.

範例: ASP.NET 3.5, C#, Excel 2003 中文版

untitled

所以需要加入style 強制用文字的format


        Download("<style> td {mso-number-format:" + "\\@" + "; text-align:center;} </style>");
    }

untitled

2. 輸出的string 無法顯示中文

因為.NET的字串是UTF-8 所以必須改用big5編碼的byte[]


        Encoding big5 = Encoding.GetEncoding(950);
        return big5.GetBytes(str);
    }

3. GridView 出現異常

"型別 'GridView' 的控制項 'GridView1' 必須置於有 runat=server 的表單標記之中。"


        return;
        //base.VerifyRenderingInServerForm(control);
    }

 

參考資料:

topcat: 解決GridView使用RenderControl取得HTML出現的問題

Avoid default formatting when exporting data from datagrid to excel.

 

 

完整程式碼下載