在开发ASP.NET web应用程序时,我们很常用到GridView控件来显示数据,那我们怎样才能将GridView中的数据导出到Excel或者Word中呢?

前提条件:

1你的GridView已经能正常显示数据了,不管你是用代码实现的,还是直接绑定数据库实现的。

2、如果你的GridView启动了分页功能,则要先将该功能关闭,即将allowpaging的属性设为false, AllowPaging="false";然后重新调用databind()或者你自己定义的显示函数,确保所有的数据都显示在GridView中,再导完数据之后,记得把allowpaging的属性值改回来。

3、在页面中添加一个"导出"按钮,当点击该按钮时执行导出动作。双击改按钮,编写事件处理函数。在用到StringWriter类的时候,要在.aspx.cs文件的头部添加命名空间:using System.IO;usingSystem.Data.SqlClient可能也要添加一下。

上面都准备好后,下面进行数据保存前对保存文件的一些设置:

设置输出文件的类型

//输出类型为Word
Response.ContentType = "application/ms-word";
//输出类型为Excel
//Response.ContentType = "application/ms-excel";

设置编码方式和内容保存的形式
Response.ContentEncoding = System.Text.Encoding.UTF8;

//设置显示的字和内容要存的形式
Response.Charset = "Word文档";

设置保存为的文件名

string dateStr = DateTime.Now.ToString("yyyyMMddHHmmss");
string fileName=System.Web.HttpUtility.UrlEncode("要保存为的文件名" +dateStr, System.Text.Encoding.UTF8);
        
//设置保存的文件名
Response.AppendHeader("content-disposition", "attachment;filename=\"" + fileName + ".doc\"");

至此保存前文件的一些设置已经完成了,下面就是将GridView中的数据保存到Word/Excel中

StringWriter oStringWriter = new StringWriter();
HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);

GridView1.RenderControl(oHtmlTextWriter);        
Response.Write(oStringWriter.ToString());
若想将多个GridView中的数据保存到同一个Word文件中,只需将之前的StringWriter、HtmlTextWriter对象释放,重新实例化一下就可以了,若不重新实例化GridView1中的数据会再写入一次。

oStringWriter = new StringWriter();
oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
GridView2.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
下面附上protected void Button1_Click(object sender, EventArgs e)中的完整代码

    protected void Button1_Click(object sender, EventArgs e)
    {
        //清除客户端当前显示
        Response.Clear();
        Response.Buffer = true;

        //输出类型为Word
        Response.ContentType = "application/ms-word";
        //输出类型为Excel
        //Response.ContentType = "application/ms-excel";

        Response.ContentEncoding = System.Text.Encoding.UTF8;

        //设置显示的字和内容要存的形式
        Response.Charset = "Word文档";

        string dateStr = DateTime.Now.ToString("yyyyMMddHHmmss");
        string fileName=System.Web.HttpUtility.UrlEncode("A卷" +dateStr, System.Text.Encoding.UTF8);
        
        //设置保存的文件名
        Response.AppendHeader("content-disposition", "attachment;filename=\"" + fileName + ".doc\"");
        this.EnableViewState = false;

        StringWriter oStringWriter = new StringWriter();
        HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);

        GridView1.RenderControl(oHtmlTextWriter);        
        Response.Write(oStringWriter.ToString());

        oStringWriter = new StringWriter();
        oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
        GridView2.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());

        Response.End(); 
    }



Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐