我有一个显示GridView的Aspx页面。 gridview将显示数据,该数据取决于从下拉菜单中选择的catergory。用户可以选择将其作为CSV文件下载(导出为CSV)。我现在想要不显示Gridview(因为它太大而常常只是挂起)而是能够从gridview下载带有数据的CSV文件。我已经成功构建了按钮,允许通过单击按钮下载此数据。但是,我现在无法在没有gridView出现的情况下打开页面。我试图注释掉Gridview代码 - 这只是打破了页面。我试图将gridview设置为Visible =“False”,但这也不起作用。我还能做些什么来防止出现gridview并将用户直接带到下载对话框?
答案 0 :(得分:0)
您可以从Code Behind在DataSet或DataTable中加载数据,然后将其直接导出到Excel / CSV,而不将其分配给GridView,例如在以下示例中将其导出到Excel:
Public Sub ExportToExcel(dt As DataTable)
If dt.Rows.Count > 0 Then
Dim tw As New System.IO.StringWriter()
Dim hw As New System.Web.UI.HtmlTextWriter(tw)
Dim dgGrid As New DataGrid()
dgGrid.DataSource = dt
dgGrid.DataBind()
'Get the HTML for the control.
dgGrid.RenderControl(hw)
'Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls")
Me.EnableViewState = False
Response.Write(tw.ToString())
Response.[End]()
End If
End Sub
如果您遇到错误,例如控件必须放在表单标记内,您可能还需要在后端添加以下代码(参考:export-data-to-excel-from-datatable-gridview-aspnet-csharp)
Public Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
C#上述代码版本:
public void ExportToExcel(DataTable dt)
{
if (dt.Rows.Count > 0) {
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=Data.xls");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
public void VerifyRenderingInServerForm(Control control)
{
// Verifies that the control is rendered
}
答案 1 :(得分:0)
将Gridview
打包到div
并在asp.net代码中将其设置为display:none
-
例如:<div id="divhidegrid" runat="server" style="display:none;" > <asp:GridView ID="gvtest" runat="server" > </div>
喜欢这个