.net 導出excel 數字文本

  public static void DataTable2Excel(System.Data.DataTable dtData)
        {
    

            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            System.Web.UI.WebControls.GridView dgExport = null;
            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;
            if (dtData != null)
            {
                curContext.Response.Clear();
                curContext.Response.BufferOutput = true;
               
                //設定輸出的字符集 
                curContext.Response.Charset = "GB2312";
                //假定導出的文件名爲tiaoma.xls 
                curContext.Response.AppendHeader("Content-Disposition", "attachment;filename= Export.xls");
                curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;//System.Text.Encoding.GetEncoding("GB2312");
                //設置導出文件的格式 
                curContext.Response.ContentType = "application/ms-excel";

                System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ZH-CN", true);
                strWriter = new System.IO.StringWriter(cultureInfo);


                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
                dgExport = new System.Web.UI.WebControls.GridView();
                dgExport.RowDataBound += (GridViewFormat);
                dgExport.DataSource = dtData.DefaultView;
                dgExport.AllowPaging = false;
                dgExport.DataBind();
                //GridView1
                dgExport.RenderControl(htmlWriter);


                //把HTML寫回瀏覽器
                curContext.Response.Write(strWriter.ToString());
                //指定寫入Excel爲文本
                //curContext.Response.Write(styleText);
                curContext.Response.End();
            }

        }


 protected static void GridViewFormat(object sender, GridViewRowEventArgs e)
        {
            //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%

            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Cells[i].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                }
            }
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章