使用 OpenXML 创建 Excel 无法打开文件

Create Excel with OpenXML does not Open File

我正在使用 OpenXML 在我的 MVC 应用程序中创建一个 Excel 文档。就代码而言,我认为我做的一切都是正确的。

C#

public FileResult GetExcelReport()
{
    // Build dataset
    var excelStream = CreateSpreadsheet(data);
    return new FileStreamResult(excelStream, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet); 
}

internal MemoryStream CreateSpreadsheet(DataSet data)
{
    var stream = new MemoryStream();
    SpreadsheetDocument ssDoc = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
    // do some stuff to make a spreadsheet

    ssDoc.Close();
    return stream;
}

JS

function createExcelReport(){
    $.ajax({
        url: "/Remote/GetExcelReport",
        type: "GET",
        dataType: "text",
        cache: false,
        data: {
            sData: // params for report
        },
        success: function(data){
            window.location.href = "/Page/Index"
        }, error: function(error){
        }
    });
}

我想让文件在没有它的情况下在浏览器中打开 downloading/saving。该过程似乎正在运行,但文件打不开。

如果我改变

SpreadsheetDocument ssDoc = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);

SpreadsheetDocument ssDoc = SpreadsheetDocument.Create("filename.xlsx", SpreadsheetDocumentType.Workbook);

(使用文件名而不是内存流),一切正常并保存到我的硬盘驱动器,但我必须导航到该位置才能打开文件。

关于我可能做错了什么有什么想法吗?提前致谢!

无论如何,我解决了我的问题。我的 AJAX 没有对响应做任何事情,所以我没有使用 AJAX 调用,而是使用 @Url.Action link --

<a href="@Url.Action("GetExcelReport","Remote")">Report</a>