MVC在实体框架外运行存储过程以导出到Excel
本文关键字:Excel 存储过程 运行 实体 框架 MVC | 更新日期: 2023-09-27 18:24:40
我在一个表中有一个列表,我使用该列表来显示我可以通过单击导出按钮生成的报告列表-然后我希望导出按钮获取问题代码并将存储过程输出导出到excel。
我不能使用实体框架,因为我使用1个存储过程,每个问题代码生成一组不同的列
[HttpPost]
public ActionResult Export(string QCode = "")
{
if (QCode != "")
{
GridView gv = new GridView() { AutoGenerateColumns = true };
// Run Stored Procedure Code Not using Entity Framework
gv.DataSource = StoredProcedure(QCode).ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=ExportQuestion_" + QCode + ".xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
return View();
}
public ActionResult Export(string QCode = "")
{
if (QCode != "")
{
GridView gv = new GridView() { AutoGenerateColumns = true };
string strSQL = "GetExcelExtract '" + QCode + "'";
DataSet DS = new DataSet();
SqlConnection SQLConn = new SqlConnection(System.Web.Configuration.WebConfigurationManager.AppSettings["ConnectionString"]);
SqlCommand SQLCmd = new SqlCommand(strSQL, SQLConn);
SQLCmd.CommandTimeout = 90;
SqlDataAdapter SQlAdpt = new SqlDataAdapter();
SQlAdpt.SelectCommand = SQLCmd;
SQLConn.Open();
SQlAdpt.Fill(DS);
SQLConn.Close();
gv.DataSource = DS;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=ExportQuestion_" + QCode + ".xls");
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.ContentType = "application/ms-excel";
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
return View();
}
我最终得到了它——希望它能有所帮助!