机器人论坛
直播中

向珍

8年用户 294经验值
私信 关注
[问答]

.NETGRIDVIEW导出EXCEL怎么操作?

请教一下大家.NETGRIDVIEW导出EXCEL怎么操作?

回帖(1)

郑涵

2020-11-4 17:52:06
protected void Button2_Click(object sender, EventArgs e)
    {
        if (this.GridView1.Rows.Count == 0)
        {
            Response.Write("";//导入到excel时,保存表里数字列中前面存在的 0 .
        Response.Clear();
        Response.Charset = "GB2312";
        Response.ContentEncoding = Encoding.UTF7;
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        this.EnableViewState = false;
        this.GridView1.AllowPaging = false;
        System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        this.GridView1.RenderControl(htw);
        Response.Write(style);
        Response.Write(sw.ToString());
        //Response.Write(dt.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //在后台中重载VerifyRenderingInServerForm()方法,否则报错为“类型"GridView"的控件"GridView1"必须放在具有 runat=server 的窗体标记内“
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Cells[3].Attributes.Add("class", "text");//在数字列前存在的 0 的列中加入 class 样式 以便保存 0
        }
    }
注:如果GricView中有分页的话,导出到Excel时就会报错.可通过修改页文件可以修正这个问题:EnableEventValidation = "false".
<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
举报

更多回帖

发帖
×
20
完善资料,
赚取积分