绿色环保
千呼万唤死出来,一生一世很精彩

 

  public static void DataTableExcel(System.Data.DataTable dtData, String FileName)
        {
            System.Web.UI.WebControls.GridView dgExport = null;
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                //设置编码和附件格式 作用是中文文件名乱码
                //System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8)
                curContext.Response.ContentType = "application/ms-excel"; // "application nd.ms-excel";
                curContext.Response.ContentEncoding = System.Text.Encoding.Default;
                curContext.Response.Charset = "gb2312";
                curContext.Response.AddHeader("content-disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
                //导出Excel文件
                strWriter = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                //为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的GridView
                dgExport = new System.Web.UI.WebControls.GridView();
                dgExport.DataSource = dtData;
                dgExport.AllowPaging = false;
                dgExport.DataBind();

      //设置导出格式为文本格式防止丢失数据
                    dgExport.Attributes.Add("style", "vnd.ms-excel.numberformat:@");

                    //设置excel单元格格式防止转换数据丢失数字
                    //for (int i = 0; i < dtData.Rows.Count; i++)
                    //{
                    //    for (int j = 0; j < dtData.Columns.Count; j++)
                    //    {
                    //        dgExport.Rows[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                    //    }
                    //}

                //下载到客户端
                dgExport.RenderControl(htmlWriter);
                curContext.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" />"+strWriter.ToString());
                curContext.Response.End();
            }

 

posted on 2012-11-24 11:16  骷髅人  阅读(1801)  评论(0编辑  收藏  举报