导出到Excel - 在MVC4中安装Office自定义

时间:2013-04-05 05:52:34

标签: c# asp.net-mvc-3 excel

我在MVC4应用程序中导出到excel文件  的 Excel中

public class ExporttoExcel : ActionResult
{
public GridView ExcelGridView { get; set; }
public string fileName { get; set; }
public int totalQuantity;
public decimal totalPrice1;
public string x1;

public ExporttoExcel(GridView gv, string pFileName, int totalQty, decimal totalPrice, string x)
{
  x1= x;
  ExcelGridView = gv;
  fileName = pFileName;
  totalQuantity = totalQty;
  totalPrice1 = totalPrice;
}
    public override void ExecuteResult(ControllerContext context)
    {
    HttpContext curContext = HttpContext.Current;
    curContext.Response.Clear();
    curContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
    curContext.Response.Charset = "";
    curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    curContext.Response.ContentType = "application/vnd.ms-excel";      
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    if (x1== "111")
    {
      htw.WriteLine("<html><head>");
      //code logic
      ExcelGridView.HeaderStyle.BackColor = Color.Yellow;
      ExcelGridView.RenderControl(htw);
      htw.WriteLine("</body></html>");
    }
    else
    {
      htw.WriteLine("Data");
      ExcelGridView.RenderControl(htw);
    }
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);
    curContext.Response.Write(sr.ReadToEnd());
    curContext.Response.End();
    }
}

发生以下错误,并且未打开excel文件。

Error : 
From: file:///d:/Program Files/Microsoft Visual Studio 10.0/Common7/IDE/PrivateAssemblies/Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.vsto did not succeed.


我的代码中有任何错误。我该怎么做才能解决这个错误。 ?
编辑:
此错误仅在IE中发生。 Firefox和Chrome会打开Excel文件。

1 个答案:

答案 0 :(得分:0)

我在本地计算机中的三个文件中添加了指定错误的位置。

Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.dll
Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn.dll.manifest
Microsoft.VisualStudio.QualityTools.LoadTestExcelAddIn

它工作正常,IE打开Excel文件。