2014-09-25 55 views
1

我有一个表中的列表,我使用该列表来显示我可以通过单击导出按钮生成的报告列表 - 然后我想要导出按钮取出问题代码并将存储过程输出导出为ex​​cel。MVC运行一个存储过程导出到实体框架外的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(); 
    } 

回答

1
 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(); 
    } 

的 - 希望它帮助!