GridView中的数据导出到Excel方法(包含处理模板列)

news/2024/7/21 7:37:41 标签: excel, server, asp.net, string, 服务器, 脚本
    今天再整理一篇有用的文章,对于GridView中数据的导出的处理问题。有时我们在GridView表格中显示的不仅仅是从数据库中读出的值,还需要加 上一些人为处理的模板列(比如删除按钮、下拉选择框、hypelinker等)。在导出后,我们往往不需要这些控件显示或者不希望以控件的形式来显示,而 是以数据的形式来展示。这就需要在导出时作一些处理,参考了一些互联网上的信息,整理如下:
 
一、导出button

   protected void export_Click(object sender, EventArgs e)

    {

        if (this.MachineList.Rows.Count == 0)

        {

            Response.Write("<script>alert(&apos;没有查找到数据,无法导出!&apos;)</script>");

        }

        else

        {

            this.MachineList.AllowPaging = false; // 将有分页的GridView中的数据全部导出到Excel

            Bind();

            Export("application/ms-excel", "设备信息.xls");

            // 换成 export("application/ms-word", "设备信息.doc"); 那么导出的就是Word格式的了.

            this.MachineList.AllowPaging = true;

            Bind();

        }       

    }

 

二、导出主函数

 public void Export(string FileType, string FileName)

    {

        string style = @"<style>.text{mso-number-format:@}</script>";//导入到excel,保存表里数字列中前面存在的 0 .

        PrepareGridViewForExport(MachineList);//将模版列显示出来

        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.MachineList.AllowPaging = false;

        System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);

        StringWriter sw = new StringWriter();

        HtmlTextWriter htw = new HtmlTextWriter(sw);

        this.MachineList.RenderControl(htw);

        Response.Write(style);

        Response.Write(sw.ToString());

        //Response.Write(dt.ToString());

        Response.End();

    }

 

    /// <summary>

    /// 重写VerifyRenderingInServerForm(Control control)方法,以确保在程序运行时,指定的GridView控件总是位于"<form runat="server"></form>"标记内.

    /// 该方法用来确认在运行时为指定的ASP.NET服务器控件呈现<form runat="server">标记.

    ///     必须位于<form runat="server">中的控件可以在呈现之前调用此方法,以便在控件被置于标记外时显示错误信息;另外,发送回或依赖于注册的脚本块的

    /// 控件应该在Control.Render()方法的重写中调用此方法.

    ///     如果回发或使用客户端脚本服务器控件没有包含在<form runat="server"> 标记中,它们将无法正常工作,这时,可以通过重写VerifyRenderingInServerForm(

    /// Control control)方法使用程序正常运行.

    /// </summary>

    /// <param name="control"></param>

    public override void VerifyRenderingInServerForm(Control control)

    {

        // Confirms that an HtmlForm control is rendered for

        //the specified ASP.NET server control at run time.

}

 

三、如果GridView存在模板列,其中包含子控件,例如CheckBox等,导出EXCEL后就会出现该区域的不规律。所以要对模板列单独处理(转载)

public  void PrepareGridViewForExport(Control gv)//模式化特殊元素 flashcong

    {

 

        LinkButton lb = new LinkButton();

        Literal l = new Literal();

        string name = String.Empty;

 

        for (int i = 0; i < gv.Controls.Count; i++)

        {

           

            if (gv.Controls[i].GetType() == typeof(LinkButton))

            {

 

                l.Text = (gv.Controls[i] as LinkButton).Text;

                gv.Controls.Remove(gv.Controls[i]);

                gv.Controls.AddAt(i, l);

 

            }

 

            else if (gv.Controls[i].GetType() == typeof(DropDownList))

            {

 

                l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;

                gv.Controls.Remove(gv.Controls[i]);

                gv.Controls.AddAt(i, l);

 

            }

 

            else if (gv.Controls[i].GetType() == typeof(CheckBox))

            {

 

                l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";

                gv.Controls.Remove(gv.Controls[i]);

                gv.Controls.AddAt(i, l);

 

            }

 

            else if (gv.Controls[i].GetType() == typeof(ImageButton))

            {

                l.Text = "图片";

                gv.Controls.Remove(gv.Controls[i]);

                gv.Controls.AddAt(i, l);

            }

 

            if (gv.Controls[i].HasControls())

            {

                PrepareGridViewForExport(gv.Controls[i]);

            }

        }

}

 

    注:对于模板列的处理还有一特殊情况,我在GridView使用时,用了<a></a>在客户端打开对话框的方法。在导出时,这一列不是模板列控件,但导出后Excel中会显示有下划线的链接,所以想去掉它。

想了很多方法,也没成功。后来我只好用了不得以的方法,多加一列文本列,用来显示链接的文本,导出前采用列隐藏的方法解决。

如果有更好的处理方法,也请各位指教!

 


http://www.niftyadmin.cn/n/1412593.html

相关文章

Distant supervision for relation extraction without labeled data论文理解

Distant supervision for relation extraction without labeled data论文理解 论文作者&#xff1a;Mike Mintz, Steven Bills, Rion Snow, Dan Jurafsky 核心词汇&#xff1a;multiclass logistic regression classifier 多类逻辑回归分类器 named entity tagger 命名实体标…

background的css 排列顺序写法?

可以按顺序设置如下属性&#xff08;可点击进入相应的css手册查看使用&#xff09;&#xff1a; background-color 背景颜色 background-image 背景图片 background-repeat 背景重复 background-attachment 背景图片是固定还是滚动 background-position 背景图片的定位 接下来我…

windows完全删除MySQL数据库

完全删除MySQL数据库 1.删除服务MySQL 进行管理员模式下cmd&#xff0c;输入net stop mysql停止服务 再输入sc delete mysql删除服务 2.卸载/删除MySQL相关的程序以及MySQL数据库 3.运行“regedit”文件&#xff0c;如图&#xff0c;打开注册表 删除注册表数据&#xff0c;通过…

ASP.Net生成多彩下拉框

开发背景&#xff1a; 有人曾经要我开发一个根据不同选择而显示不同颜色的管理工具。我开始考虑利用下拉框来实现条目背景及显示颜色根据条目名称不同而进行变化&#xff0c;根据这个思路我 在网上搜了半天也没有找到任何相关的解决方案&#xff0c;最后我想到了一个比当初…

Git 版本导致 clone 故障

问题描述&#xff1a; git clone 报错如下&#xff1a; Initialized empty Git repository in /root/project_php/.git/ error: The requested URL returned error: 401 Unauthorized while accessing http://tone.verru.cn:88/project_php.git/info/refsfatal: HTTP request f…

js中this关键字的作用

this中的几种情况1.普通函数中的this window2.构造函数中的this 是当前构造函数创建的对象在new这个构造函数的时候会在内存中创建一个对象,此时会让this指向刚创建好的这个对象3.方法中的this 方法所属的对象,谁调用这个方法this就指向谁4.事件处理函数中的this 事件源 谁调用…

梅花雪树控件的使用及下载

梅花雪树2.0下载mztreeview2.0.rar 梅花雪树1.0下载mztreeview10.js 梅花雪树1.0控件 有以下属性和方法。 属性 MzTreeView 类的一些属性&#xff1a; 属性名 类型 属性的具体说明 MzTreeView.nodes 集合 服务器端给树指定数据源时数据存放的对象&#xff0c;具体存放格式如&…