我有一个关于从gridview中导出excel一些过滤结果的问题。我使用了此链接中的解决方案http://forums.asp.net/t/1991866.aspx?Export%20filtered%20results%20to%20excel%20in%20MVC%204 这一切都很好,只是我导出的表有很多来自外键的ID列,我不能导出数字,我需要数据。我有一个变量,我保持与我导出的表相关的所有表的选择连接但我不知道如何在此变量和保持过滤结果来自Session的变量之间建立连接。你可以帮帮我吗?谢谢。
答案 0 :(得分:0)
在Page_Load中显示所有记录。
导出时我只选择与Scott相关的订单
protected void Page_Load(object sender,EventArgs e) { if(!IsPostBack) { DataTable dt = BindGridView(); GridView1.DataSource = dt; GridView1.DataBind(); } }
private DataTable BindGridView(string name = null)
{
string connectionString = "Data Source=.SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True";
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand();
if (name != null)
{
cmd.CommandText = "SELECT * FROM ORDERS WHERE Name='" + name + "'";
}
else
{
cmd.CommandText = "SELECT * FROM ORDERS";
}
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
return dt;
}
}
protected void ExportToExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=exportdata.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView gv = new GridView();
gv.DataSource = BindGridView("Scott"); // Seelct all the order where Name='Scott' - my filter query
gv.DataBind();
gv.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
}