将Paged ListView的所有行导出到Excel

时间:2011-03-06 05:32:52

标签: c# asp.net excel listview webforms

在ASP.NET 4.0 webforms中,我试图通过取消分页ListView(卡车)数据源来将分页的ListView控件导出到Excel文件:

dsTrucks.EnablePaging = false;

对于非分页的ListView控件,我可以让它工作。

这是尝试“取消页面”然后导出ListView控件:

    // Nuke the current page.
    Response.Clear();

    // Setup the response header.
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=Trucks.xls");
    Response.ContentType = "application/vnd.ms-excel";
    Response.Charset = "";

    // Turn off view state.
    this.EnableViewState = false;

    // Create a string writer.
    var stringWriter = new StringWriter();

    // Create an HTML text writer and give it a string writer to use.
    var htmlTextWriter = new HtmlTextWriter(stringWriter);

    // Disable paging so we get all rows.
    dsTrucks.EnablePaging = false;

    // Render the list view control into the HTML text writer.
    listViewTrucks.DataBind();
    listViewTrucks.RenderControl(htmlTextWriter);

    // Grab the final HTML out of the string writer.
    string output = stringWriter.ToString();

    // Write the HTML output to the response, which in this case, is an Excel file.
    Response.Write(output);
    Response.End();

没有错误,但Excel文件中的输出仍然只是ListView控件的一页而不是所有行。

关于从哪里开始使用它的任何想法?

谢谢, 亚当

1 个答案:

答案 0 :(得分:0)

只是一个猜测,但可能是EnablePaging只能在控件的OnInit()上运行,而且从代码中调用它时已经太晚了。

也许您可以将PageSize设置为某个MAXINT值并将所有结果强制为一个页面?