Asp.net中导出成Excel等格式

我们做一个测试程序:
1、在空白页上创建一个GridView,给它指定一个数据源,填充一些测试数据(此例中是GridView1)。
2、给页面添加一个按钮(此例中是btnExport),在按钮的单击事件中填入如下代码:
protected void btnExport_Click(object sender, EventArgs e)
{
        Response.Clear();
        Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
        Response.AppendHeader("content-disposition", "attachment;filename=\"" + HttpUtility.UrlEncode("[" + DateTime.Now.ToString("yyyy-MM-dd") + "]", System.Text.Encoding.UTF8) + ".xls\"");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        // If you want the option to open the Excel file without saving then
        // comment out the line below
        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
}
3、重载方法VerifyRenderingInServerForm,否则VS编译器报错。
public override void VerifyRenderingInServerForm(Control control)
{
}
4、运行页面,单击按钮,弹出提示框,要你选择保存或打开一个以当前时间命名的Excel文件。

注意事项:若表格中有中文必须将编码格式设置为gb2312,如下:
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
必须重载VerifyRenderingInServerForm方法。
还可以导出成各种形式的文档,只需把Response.ContentType的值设置成别的就可以,具体值可以从网上查到,如要导出成Word格式可以将Response.ContentType的值设置成"application/word.doc"。

posted @   Teddy  阅读(937)  评论(1编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示