我正在使用asp.net,我有以下c#方法将网格视图数据导出到Excel工作表,这个方法是通过ImageButton点击事件调用的:
public void GridToExcel()
{
if (berthOccupancyDataGridView.Rows.Count > 0)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=BerthOccupancy.xls");
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
berthOccupancyDataGridView.RenderControl(htw);
if (reportType == "Year To Date")
{
foreach(GridView gv in gridViewList)
{
gv.RenderControl(htw);
}
}
else
{
recapGridView.RenderControl(htw);
}
Response.Write(sw.ToString());
Response.End();
}
}
我有List存储动态创建的GridViews。问题是图像按钮触发PostBack并将此列表设置为null。我尝试了很多方法来阻止它进行PostBack,例如使用OnClienClick =" return false;"但它没有用。 我尝试使用ScriptManager和WebMethods,但它需要将方法设置为static并将方法设置为static会显示以下错误:
错误2非静态字段,方法或属性需要对象引用“System.Web.UI.Page.Response.get'
错误5非静态字段,方法或属性需要对象引用' BerthOccypancyForm.berthOccupancyDataGridView'
有没有办法在不使用WebMethods和PageMethods的情况下使用AJAX调用此方法?
感谢您的帮助..
答案 0 :(得分:0)
我通过使用以下代码在PostBack中保留列表数据和变量来解决问题:
(这个答案的问题是会话数据在20分钟后默认超时。会话不用于存储大数据,例如gridviews)
这个用于保存GridViewList数据:
public List<GridView> Code
{
get
{
if (HttpContext.Current.Session["Code"] == null)
{
HttpContext.Current.Session["Code"] = new List<GridView>();
}
return HttpContext.Current.Session["Code"] as List<GridView>;
}
set
{
HttpContext.Current.Session["Code"] = value;
}
}
这个用于保存字符串数据:
public string RT
{
get
{
if (HttpContext.Current.Session["RT"] == null)
{
HttpContext.Current.Session["RT"] = "" ;
}
return HttpContext.Current.Session["RT"] as string;
}
set
{
HttpContext.Current.Session["RT"] = value;
}
}
答案 1 :(得分:0)
所以我在更新面板中有一个gridview
控件,它基本上为用户提供了一个数据列表,如下所示:
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView runat="server" ID="transactionGrid" CssClass="table table-bordered table-condensed table-striped"
AllowPaging="true" PageSize="8" AutoGenerateColumns="false" ShowHeaderWhenEmpty="true"
OnRowCommand="transactionGrid_RowCommand"
OnRowDataBound="transactionGrid_RowDataBound"
OnPageIndexChanging="transactionGrid_PageIndexChanging">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<a runat="server" href="~/PayrollManagement/Transaction/TransactionEntry.aspx" class="btn btn-success btn-outline btn-sm"><i class="fa fa-plus fa-fw"></i> Add</a>
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton runat="server" ID="cmdPrint" CssClass="btn btn-success btn-outline ttip btn-sm" ToolTip="Print Batch" data-toggle="tooltip"
CommandName="printBatch" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
<span><i class=" fa fa-print fa-fw"></i></span>
</asp:LinkButton>
<asp:LinkButton runat="server" ID="cmdExportCSV" CssClass="btn btn-success btn-outline ttip btn-sm" ToolTip="Export Batch" data-toggle="tooltip"
CommandName="exportBatch" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
<span><i class=" fa fa-envelope fa-fw"></i></span>
</asp:LinkButton>
<asp:LinkButton runat="server" ID="cmbEditBatch" CssClass="btn btn-primary btn-outline ttip btn-sm" ToolTip="Edit Batch" data-toggle="tooltip"
CommandName="editBatch" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
<span><i class=" fa fa-pencil fa-fw"></i></span>
</asp:LinkButton>
<asp:LinkButton runat="server" ID="cmdPost" CssClass="btn btn-danger btn-outline ttip btn-sm" ToolTip="Post Batch" data-toggle="tooltip"
CommandName="postBatch" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>">
<span><i class=" fa fa-archive fa-fw"></i></span>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Batch ID" DataField="HEADERID" />
<asp:BoundField HeaderText="Payroll Name" DataField="PAYROLLNAME" />
<asp:BoundField HeaderText="Date Created" DataField="DATECREATED" dataformatstring="{0:MM/dd/yyyy}" htmlencode="false" />
<asp:BoundField HeaderText="Created By" DataField="CREATEDBY" />
<asp:BoundField HeaderText="Batch Date" DataField="BATCHDATE" dataformatstring="{0:MM/dd/yyyy}" htmlencode="false" />
<asp:BoundField HeaderText="Farm Name" DataField="FARMNAME" />
<asp:BoundField HeaderText="Batch Status" DataField="STATUSDESC" />
<asp:BoundField HeaderText="Batch Desc" DataField="BATCHDESC" />
</Columns>
<PagerStyle CssClass="pagination-ys" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cmdSearch" EventName="click" />
<asp:AsyncPostBackTrigger ControlID="cmdPostBatch" EventName="click" />
</Triggers>
</asp:UpdatePanel>
<div hidden="hidden">
<iframe src="../CSVExport/ExportToCsv.aspx" runat="server" id="csvFrame"></iframe>
</div>
在gridview中,您可以看到有一个exportBatch
链接按钮,该按钮分配给每一行。因此,当用户单击exportBatch
按钮时,我运行我的代码来编译csv,在您的情况下,它将导出到excel。
所以这是rowcommand method
:
protected void transactionGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
int index;
GridViewRow row;
int batchID;
processPayBatch dal = new processPayBatch();
switch (e.CommandName)
{
case "exportBatch":
index = Convert.ToInt32(e.CommandArgument);
row = transactionGrid.Rows[index];
batchID = Convert.ToInt32(row.Cells[1].Text);
Session["csvbatch"] = batchID;
csvFrame.Attributes["src"] = "/CSVExport/ExportToCsv.aspx";
//Download the CSV file.
ScriptManager.RegisterStartupScript(this, this.GetType(), "", "window.frames[0].document.forms[0].submit();", true);
break;
}
}
因此,当点击行按钮时,我会在iframe中提交表单。这是ExportToCsv页面的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) {
processPayBatch dal = new processPayBatch();
int batchID = (int)Session["csvbatch"];
Session["csvbatch"] = null;
dal.ExportToCSV(batchID);
string csv = dal.csvFile;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.Output.Write(csv);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
查询数据库并检索必要的信息并将其编译为csv文件。
我选择使用iframe的原因是因为如果我必须在后面的gridview代码中执行它(因为更新面板),response.write没有运行。
答案 2 :(得分:0)
谢谢你们的建议。我能够以这种方式解决它。
我添加了一个静态类,它有静态List和静态字符串。我在WebForm中称这个类。这样在PostBack期间保留GridViews的数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
/// <summary>
/// Summary description for Global
/// </summary>
public static class Global
{
public static List<GridView> GridViewList = new List<GridView>();
public static string ReportType = "";
}
以下C#函数使用静态类中的数据导出到excel。
public void GridToExcel()
{
if (berthOccupancyDataGridView.Rows.Count > 0)
{
Response.Clear();
//HttpContext.Current.Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=BerthOccupancy.xls");
//HttpContext.Current.Response.Charset = "";
Response.ContentType = "text/csv";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
berthOccupancyDataGridView.RenderControl(htw);
if (Global.ReportType == "Year To Date")
{
foreach (GridView gv in Global.GridViewList)
{
gv.RenderControl(htw);
}
}
else if(Global.ReportType == "Monthly")
{
recapGridView.RenderControl(htw);
}
Response.Write(sw.ToString());
Response.End();
}
}