---
title: "Asp.net 导出Excel的方法！"
author: "topcss"
date: "2011-03-11T14:44:58Z"
tags: []
categories: ["编程语言"]
slug: "asp-net-excel"
draft: false
lastmod: "2011-03-11T14:44:58Z"
id: 953986
url: "https://topcss.iteye.com/blog/953986"
---

同事在项目遇到一个需求：多项批量检查数据并将错误数据用Excel的方式导出，以备查看。

   听起来很简单的，但遇到一个问题。当后台生成Excel时会产生Excel进程，并且这些Excel进程会越来越多。本地调试时可以回收这些进程，但远程访问时出现却不能自动GC和手动回收。

    之前考虑到可能是因为发布后权限不足。然后我们到网上查了资料，发现始终都无法回收和杀死这些Excel进程。于是，俺想到下面的方法。并测试通过！写此文章，仅作备忘。

 

 

1、新建一个文件：ExcelExport.aspx

 

```
        private void OutExcelStream(DataSet ds)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "GBK";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + sqlflag + ".xls");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GBK");
            Response.ContentType = "application/ms-excel";
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            if (ds != null)
            {
                DataGrid dataGrid = new DataGrid();
                dataGrid.DataSource = ds.Tables[0].DefaultView;
                dataGrid.DataBind();
                dataGrid.RenderControl(oHtmlTextWriter);
            }

            Response.Output.Write(oStringWriter.ToString());
            Response.Flush();
            Response.End();
        }
```

 

 在Page\_Load方法中添加

 

```
            string SessionValue = String.Empty;
            if (Request.Params["sql"] != null)
            {
                SessionValue=Request.Params["sql"].ToString();//得到Session
                DataSet ds = (DataSet)Session[SessionValue];
                OutExcelStream(ds);//保存该Session的对象
                Session.Remove(SessionValue);//回收该Session
            }
```

 

 

2、在检查数据的代码里面，把查出来的错误数据DataSet保存到Session中（Session\["xxx"]=DataSetObject;）。并将xxx返回到客户端。

 

3、但客户端点击按钮时，打开ExcelExport.aspx，并传入session的值（Response.Redirect("ExcelExport.aspx?sql=a0001");）。