1

所以我有这个方法:

public Microsoft.Office.Interop.Excel.Worksheet createDoc()
{
    try
    {       
        app = new Microsoft.Office.Interop.Excel.Application();
        app.Visible = true;
        workbook = app.Workbooks.Add(1);
        worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
    }
    catch (Exception e)
    {
        Console.Write("Error");
    }
    finally
    {
    }
    return worksheet;
}

我需要能够返回此工作表并将其附加到我认为的 html iframe 中。我在 Visual Studio 中使用 MVC4。这是迄今为止我用来获取 JSONResults 的代码,但我从来没有处理过这个问题。

    $.getJSON("/exceldocumentmethod", function (results) {
    });

有什么建议吗?

4

1 回答 1

0

您不应该为此使用 JSON。您应该有一个控制器操作,该操作将 Excel 文件直接返回到具有正确 Content-Type 和 Content-Disposition 标头的响应。然后将src的指向iframe这个控制器动作。不要使用任何$.getJSON方法,他们不会帮助你。

因此,例如,您可以拥有以下 iframe:

<iframe src="@Url.Action("ExcelDoc", "Home")"></iframe>

您的 ExcelDoc 操作可能如下所示:

public ActionResult ExcelDoc()
{
    var doc = Server.MapPath("~/App_Data/example.xls");
    return File(doc, "application/vnd.ms-excel");
}

对于 Excel2007 及更高版本的 .xlsx 文件,正确的 Content-Type 是application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.

我还注意到您正在使用 Excel Interop 在服务器上动态生成文档。此库依赖于安装在服务器上的 Excel,并非设计用于 Web 应用程序(服务器环境)。不要使用它。如果要在服务器上动态生成 Excel 文件,可以使用Open XML SDK. 下面example on MSDN介绍如何使用此 SDK 生成 Excel 电子表格。

于 2013-03-30T17:48:34.200 回答