GridView導出數據到Excel(形如身份證等數據的處理)

//以下是一個DEMO 

protected void Page_Load(object sender,EventArgs e)

        {
            DataTable dt = CreateTable();
            //填充數據
            InitialDataTable(dt);
            //綁定
            BindData(dt);
        }


        private void BindData(DataTable dt)
        {
            grdInfo.DataSource = dt;
            grdInfo.DataBind();
        }


        private void InitialDataTable(DataTable dt)
        {
            for (int i = 0; i < 100; i++)
            {
                DataRow dr = dt.NewRow();
                dr["姓名"] = "姓名" + i.ToString("000");
                dr["年齡"] = i.ToString();
                dr["性別"] = "男";
                dr["身份證"] = "123456789012345"+i.ToString("000");
                dt.Rows.Add(dr);
            }
        }


        private DataTable CreateTable()
        {
            DataTable dtTemp = new DataTable();
            DataColumn clmXm = new DataColumn("姓名", typeof(System.String));
            dtTemp.Columns.Add(clmXm);
            DataColumn clmNl = new DataColumn("年齡", typeof(System.String));
            dtTemp.Columns.Add(clmNl);
            DataColumn clmXb = new DataColumn("性別", typeof(System.String));
            dtTemp.Columns.Add(clmXb);
            DataColumn clmSfz = new DataColumn("身份證", typeof(System.String));
            dtTemp.Columns.Add(clmSfz);
            return dtTemp;
        }

protected void btnExport_Click(object sender, EventArgs e)
        {
            //可以用以下兩種方法來導出數據
            //方法1.
            /*用下面方法導出形如身份證的數據到Excel中時,需要在導出前給身份證所在Cell數據添加樣式
             foreach (GridViewRow dg in grdInfo.Rows)
             {
                dg.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
                string a=dg.Cells[3].Text;
             }
              或者
              protected void grdInfo_RowDataBound(object sender, GridViewRowEventArgs e)
             {
               if (e.Row.RowType == DataControlRowType.DataRow)
               {
                 //3表示身份證所在列
                 e.Row.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:   @; ");
               }
             }
            */
            //有數據顯示的地方有黑色邊框,其餘爲空白
            Export(grdInfo, "application/vnd.ms-excel", "data.xls");


            //方法2
            /* 
            如果用下面的方法來導出形如身份證的數據到Excel中
            通過以下語句,不能達到目的
            foreach (GridViewRow dg in grdInfo.Rows)
            {
                dg.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat: @;");
                string a = dg.Cells[3].Text;
            }
            或者
            protected void grdInfo_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    //3表示身份證所在列
                    e.Row.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:   @; ");
                }
            }
            需要在<td>標籤中加入樣式<td style=vnd.ms-excel.numberformat:@>
            */
            //和默認Excel一樣,有默認格線
            Export1(grdInfo, "", "data.xls");
        }

public void Export(System.Web.UI.Control source, string fileType, string fileName)
        {
            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.Buffer = true;
            response.Charset = "UTF-8"; //default-value
            response.ContentEncoding = System.Text.Encoding.UTF7;
            response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString());
            response.ContentType = fileType;
            source.Page.EnableViewState = false;
            System.IO.StringWriter sw = new System.IO.StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            source.RenderControl(hw);
            response.Write(sw.ToString());
            response.End();
        }
        public static void Export1(GridView source, string fileType, string fileName)
        {
            if (source.Rows.Count > 0)
            {
                HttpContext ctx = HttpContext.Current;
                StringWriter sw = new StringWriter();
                sw.WriteLine("<htmlxmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
                sw.WriteLine("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
                sw.WriteLine("<head>");
                sw.WriteLine("<!--[if gte mso 9]>");
                sw.WriteLine("<xml>");
                sw.WriteLine(" <x:ExcelWorkbook>");
                sw.WriteLine("  <x:ExcelWorksheets>");
                sw.WriteLine("   <x:ExcelWorksheet>");
                sw.WriteLine("    <x:Name>data</x:Name>");
                sw.WriteLine("    <x:WorksheetOptions>");
                sw.WriteLine("      <x:Print>");
                sw.WriteLine("       <x:ValidPrinterInfo />");
                sw.WriteLine("      </x:Print>");
                sw.WriteLine("    </x:WorksheetOptions>");
                sw.WriteLine("   </x:ExcelWorksheet>");
                sw.WriteLine("  </x:ExcelWorksheets>");
                sw.WriteLine("</x:ExcelWorkbook>");
                sw.WriteLine("</xml>");
                sw.WriteLine("<![endif]-->");
                sw.WriteLine("</head>");
                sw.WriteLine("<body>");
                sw.WriteLine("<table>");
                for (int i = 0; i < source.Rows.Count; i++)
                {
                    if (i == 0)
                    {
                        sw.WriteLine("<tr>");
                        for (int j = 0; j < source.Columns.Count; j++)
                        {
                            sw.WriteLine("<td><strong>" + source.Columns[j].HeaderText + "</strong></td>");
                        }
                        sw.WriteLine("</tr>");
                    }
                    sw.WriteLine("<tr>");
                    for (int j = 0; j < source.Columns.Count; j++)
                    {
                        //sw.WriteLine("<td>" + source.Rows[i].Cells[j].Text + "</td>");
                        //j==3表示身份證所在列
                        if (j == 3)
                        {
                            //加上這句,像身份證需要加入style=vnd.ms-excel.numberformat:@這句,
                            //否則會以科學計數法顯示數據
                            sw.WriteLine("<td style=vnd.ms-excel.numberformat:@>" + source.Rows[i].Cells[j].Text + "</td>");
                        }
                        else
                        { sw.WriteLine("<td>" + source.Rows[i].Cells[j].Text + "</td>"); }
                    }
                    sw.WriteLine("</tr>");
                }
                sw.WriteLine("</table>");
                sw.WriteLine("</body>");
                sw.WriteLine("</html>");
                sw.Close();
                ctx.Response.Clear();
                ctx.Response.Buffer = true;
                ctx.Response.Charset = "UTF-8";
                source.Page.EnableViewState = false;
                ctx.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName + "");
                ctx.Response.ContentType = "application/ms-excel";
                ctx.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                ctx.Response.Write(sw);
                ctx.Response.End();
            }
        }

public override void VerifyRenderingInServerForm(Control control)
        {
        }

      //方法1時,也可以在這裏設置樣式
        protected void grdInfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //3表示身份證所在列
                e.Row.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:   @; ");
            }
        }


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