一、首先设置aspx页面EnableEventValidation="false"如下:
二、页面按钮
三、后台关键代码
四、注
五、特别提示
数据如:0011,保持原样导出则在GridView相应的列内容前加 (即空格即可)
如:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FieldObjSearch.aspx.cs"
Inherits="Unitop.JGXT2010.DAS.FieldObjSearch" EnableEventValidation="false" %>
二、页面按钮
<asp:Button ID="btnExport" runat="server" Text="" OnClick="btnExport_Click" />
三、后台关键代码
//导出到Excel按钮
protected void btnExport_Click(object sender, EventArgs e)
{
Export("application/ms-excel", "字段数据.xls");
}
//导出到Excel
private void Export(string FileType, string FileName)
{
//以下三行可选,如果没有的话导出的只是当前页数据,没有其他页数据
//gvFieldData.AllowPaging = false;
//gvFieldData.AllowSorting = false;
//GetFieldInfo(false, "obj_name"); //这里是你绑定gridview的方法
gvFieldData.Columns[7].Visible = false; //导出时隐藏操作列
gvFieldData.BottomPagerRow.Visible = false; //隐藏分页行
//string style = @"<style> .text { mso-number-format:\@; } </script> ";
Response.Clear();
Response.Buffer = true;
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); // 中文
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
//此句可解决中文导出后成为韩文的问题,当然也可以解决乱码的问题Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.gvFieldData.RenderControl(oHtmlTextWriter);
//Response.Write(style);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}
//这个方法是配合导出Excel功能,内容不用写
public override void VerifyRenderingInServerForm(Control control)
{
}
四、注
/*
* 如果按钮放在UpdatePanel中则要为UpdatePanel添加
<Triggers>
<asp:PostBackTrigger ControlID="btnExport" />
</Triggers>
*/
五、特别提示
数据如:0011,保持原样导出则在GridView相应的列内容前加 (即空格即可)
如:
<asp:TemplateField HeaderText="序列号" SortExpression="bm" HeaderStyle-CssClass="headerCss">
<ItemTemplate>
<%#StringOP.GetRationLenContent(Eval("bm"), 10)%>
</ItemTemplate>
</asp:TemplateField>