1、GridView导出Excel的方法一、带有复选框的导出 excel文件protected void dc_Click(object sender, EventArgs e)Export(“application/ms-excel“, “预订已通过人员.xls“);/“预订已通过人员.xls“为excel文件的表头private void Export(string FileType, string FileName)Response.ContentEncoding = System.Text.Encoding.UTF7;Response.Clear();Response.Buffer = f
2、alse;Response.Charset = “GB2312“;Response.AppendHeader(“Content-Disposition“, “attachment;filename=exl.xls“);Response.ContentEncoding = System.Text.Encoding.GetEncoding(“GB2312“);Response.ContentType = “application/ms-excel“;Response.Write(“);this.EnableViewState = false;/转换为table 表格HtmlTable ht = n
3、ew HtmlTable();ht.Border = 1;HtmlTableRow htrt = new HtmlTableRow();HtmlTableCell htct = new HtmlTableCell();htct.ColSpan = 15;htct.Align = “center“;htct.InnerHtml = “预订已通过人员“;htrt.Cells.Add(htct);ht.Rows.Add(htrt);HtmlTableRow htrh = new HtmlTableRow();string strArray = “ID“, “领取ID“, “工号“, “姓名“, “性
4、别“, “部门“, “工种“, “状态“, “领取类型“, “代领人“, “物品“, “预订时间“,“审核时间“, “数量“, “物品型号“,“接收人签字“ ;for (int i = 0; i “ + strArrayi + “;htrh.Cells.Add(htc);ht.Rows.Add(htrh);for (int i = 0; i = 1 System.IO.StringWriter oStringWriter = new System.IO.StringWriter();HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStr
5、ingWriter);/ht.Attributes.Add(“style“, “vnd.ms-excel.numberformat:“);ht.RenderControl(oHtmlTextWriter);Response.Write(oStringWriter.ToString();Response.End();/未将GridView放到runat=“server“里public override void VerifyRenderingInServerForm(Control control)二、不带复选框的导出 excel文件/在 gridview绑定时进行设置导出的 excel文件为文
6、本形式/ydwp.DataSource = dt;/ydwp.Attributes.Add(“style“, “vnd.ms-excel.numberformat:“);/ydwp.DataBind();/ 导出列表信息到Excelprotected void dc_Click(object sender, EventArgs e)Export(“application/ms-excel“, “已领取人员表.xls“);private void Export(string FileType, string FileName)ydwp.AllowPaging = false;Response.C
7、harset = “GB2312“;Response.ContentEncoding = System.Text.Encoding.UTF7;Response.Clear();Response.Buffer = false;Response.Charset = “GB2312“;Response.AppendHeader(“Content-Disposition“, “attachment;filename=exl.xls“);Response.ContentEncoding = System.Text.Encoding.GetEncoding(“GB2312“);Response.Conte
8、ntType = “application/ms-excel“;Response.Write(“);/this.EnableViewState = false;System.IO.StringWriter oStringWriter = new System.IO.StringWriter();HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);ydwp.RenderControl(oHtmlTextWriter);Response.Write(oStringWriter.ToString();Response.End();/注:三、在导出的 excel文件中往往需要将 excel文件设置为文本的形式需要在方法或者绑定 gridview中加.Attributes.Add(“style“, “vnd.ms-excel.numberformat:“);