Asp.net中导出Excel文档(Gridview)

主要思路,通过GridView来导出文档。
新建一个Aspx页面,页面创建GridView控件,后台绑定好数据源。
然后load中直接打印即可导出

前台的GridView

<asp:GridView ID="GridView1" BorderColor="Black" runat="server" AutoGenerateColumns="False"
Font-Size="12px" Width="656px" AllowSorting="True" Height="172px">
<Columns>
<asp:BoundField DataField="Name" HeaderText="姓名" />
<asp:BoundField DataField="Sex" HeaderText="性别" />
<asp:BoundField DataField="BirthDay" HeaderText="出生日期" />
<asp:BoundField DataField="StudentId" HeaderText="身份证号" />
<asp:BoundField DataField="JieduId" HeaderText="借读证号" />
<asp:BoundField DataField="Familymemberinfo_Name1" HeaderText="第一监护人姓名" />
</Columns>
<HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" />
<RowStyle HorizontalAlign="Center" />
<PagerStyle HorizontalAlign="Center" />
</asp:GridView>

后台:

        /// <summary>
/// 定义导出Excel的函数
/// </summary>
/// <param name="FileType"></param>
/// <param name="FileName"></param>
private void Export(string FileType, string FileName)
{
for (int i = ; i < GridView1.Rows.Count; i++)
{
//这里给指定的列编辑格式,将数字输出为文本,防止数字溢出
GridView1.Rows[i].Cells[].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
}
Response.Charset = "GB2312";
//Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
} /// <summary>
/// 此方法必重写,否则会出错
/// </summary>
/// <param name="control"></param>
public override void VerifyRenderingInServerForm(Control control)
{
}
上一篇:asp.net中导出Excel的方法


下一篇:vs2017 未能完成操作。不支持此接口