0

在我的 aspx 页面上,我有一个Usercontrol包含 的Gridview,它的数据是根据从 aspx 页面传递到 UserControl 的参数动态加载的,我称之为QuotesReport1.

导出运行时,它只将布局导出到 中Spreadsheet,而没有任何 gridview 的数据,例如:


<style>
    body
    {
        margin: 0px;
    }
</style>
<div>
</div>

我的导出代码是:

protected void Page_Load(object sender, EventArgs e)
{
    string toDate = "";
    string fromDate = "";

    toDate = Request.QueryString.Get("toDate");
    fromDate = Request.QueryString.Get("fromDate");


    QuotesReport1.ToDate = DateTime.Parse(toDate);
    QuotesReport1.FromDate = DateTime.Parse(fromDate);
    QuotesReport1.Status = QuotesReport.quoteStatus.PENDING_REVIEW;

    string attachment = "attachment; filename=Quotes_Pending.xls";
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    QuotesReport1.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.End();
}
public override void VerifyRenderingInServerForm(Control control) { }

在 UserControl 内部,运行 SQL 查询,该查询返回一个 DataTable,然后将其绑定到 UserControl 内部的 Gridview,大致如下:

SQLData da = new SQLData();
GridView1.DataSource = da.SGetDataTable(query);
GridView1.DataBind();
4

1 回答 1

0

我有最简单的方法

public class ExcelUtility
{
    public static void ToExcel(object dataSource)
    {
        GridView grid = new GridView { DataSource = dataSource };
        grid.DataBind();

        StringBuilder sb = new StringBuilder();
        foreach (TableCell cell in grid.HeaderRow.Cells)
            sb.Append(string.Format("\"{0}\",", cell.Text));
        sb.Remove(sb.Length - 1, 1);
        sb.AppendLine();

        foreach (GridViewRow row in grid.Rows)
        {
            foreach (TableCell cell in row.Cells)
                sb.Append(string.Format("\"{0}\",", cell.Text.Trim().Replace("&nbsp;", string.Empty)));
            sb.Remove(sb.Length - 1, 1);
            sb.AppendLine();
        }
        ExportToExcel(sb.ToString());
    }

    private static void ExportToExcel(string data)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Report.csv");
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        HttpContext.Current.Response.ContentType = "text/csv";
        HttpContext.Current.Response.Write(data);
        HttpContext.Current.Response.End();
    }
}

使用:

   string result = ExcelUtility.ToExcel(_db.FindAll());
   ExcelUtility.ExportToExcel(result);
于 2012-12-26T12:59:03.607 回答