gpt4 book ai didi

javascript - 使用 getJSON 返回 Excel 电子表格

转载 作者:行者123 更新时间:2023-11-28 09:15:29 25 4
gpt4 key购买 nike

所以我有这个方法:

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) {
});

有什么建议吗?

最佳答案

您不应该为此使用 JSON。您应该有一个 Controller 操作,将 Excel 文件直接返回到具有正确 Content-Type 和 Content-Disposition header 的响应。然后将 iframesrc 指向此 Controller 操作。不要使用任何 $.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 电子表格。

关于javascript - 使用 getJSON 返回 Excel 电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15720905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com