某些计算机上导出到Excel失败

时间:2016-08-04 07:33:47

标签: c# asp.net-mvc excel

我们正在开发一个Web应用程序,我们的一些查询结果需要导出到Excel。我们使用以下C#代码导出:

<head>
  <meta charset="ISO-8859-1">
  <title>Print Reverse of a number</title>
</head>

<body>
  <table>
    <tr>
      <td>
        Enter number
      </td>
      <td>
        <input type="number" size="20" name="nid">
      </td>
    </tr>
    <tr>
      <td align="center" colspan="2">
        <input type="submit" value="submit" onclick="display()">
      </td>
    </tr>
  </table>
</body>

我返回结果的部分视图如下:

System.Web.HttpContext ctx = System.Web.HttpContext.Current;
CurrentPackingListModel.Voyage.ShipmentDataContext = ShipmentDataContext;
ctx.Response.Clear();
string filename = "ApprovalForm.xls";
ctx.Response.AddHeader("content-disposition", "attachment;filename=" + filename);
ctx.Response.ContentType = "application/vnd.ms-excel";
ctx.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
ctx.Response.Charset = "UTF-8";
return View("../Packing/_ExportApprovalForm", CurrentPackingListModel);

但导出到Excel可以在某些机器上运行,但不适用于其他机器。这种情况最近才开始发生。

有没有可能的解决方案来解决这个问题,而无需重新编写整个导出功能?

2 个答案:

答案 0 :(得分:2)

道歉这不是答案,但我无法评论,因为我有低代表。

是否在未运行的机器上安装了Excel?从我的内存中必须安装excel才能导出。我过去使用Epplus来解决这个问题。

您是否可以添加一些异常处理并记录此发布的内容,以便从错误中获取更多详细信息?即使您只是将它写入机器上的txt文件。

抱歉,我没有任何实际答案。

答案 1 :(得分:-1)

代码下面的代码对您有所帮助:

public void ExportToExcel()
{
  DataGrid dgGrid = new DataGrid();
  dgGrid.DataSource = /*Give your data source here*/;

  dgGrid.DataBind();
  System.Web.HttpContext.Current.Response.ClearContent();
  System.Web.HttpContext.Current.Response.Buffer = true;
  System.Web.HttpContext.Current.Response.AddHeader("content-disposition",    string.Format("attachment; filename={0}", "Data Report.xls"));
  System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
  System.Web.HttpContext.Current.Response.Charset = "";
  System.IO.StringWriter sw = new System.IO.StringWriter();
  HtmlTextWriter htw = new HtmlTextWriter(sw);
  dgGrid.RenderControl(htw);
  System.Web.HttpContext.Current.Response.Output.Write(sw.ToString());
  System.Web.HttpContext.Current.Response.Flush();
  System.Web.HttpContext.Current.Response.End();
}
相关问题