MVC 4 Export to Excel Failing

≡放荡痞女 提交于 2019-12-25 02:06:30

问题


I have the following code in a controller in and MVC 4 application

    Response.AddHeader("Content-Disposition", "attachment; filename=export.xml");
    Response.AddHeader("Content-type", "vnd.openxmlformats-officedocument.spreadsheetml.sheet");

    var rows = data.Split('\n');
    var sheet = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine;
    sheet += "<?mso-application progid=\"Excel.Sheet\"?>" + Environment.NewLine;

    sheet += "<ss:Workbook xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:html=\"http://www.w3.org/tr/rec-html40\">" + Environment.NewLine;
    sheet += "<ss:Worksheet ss:Name=\"Sheet1\">" + Environment.NewLine;
    sheet += "<ss:Table>" + Environment.NewLine;

    foreach (var r in rows)
    {
        sheet += "<ss:Row>" + Environment.NewLine;

        var columns = r.Split(',');

        foreach (var column in columns)
        {
            sheet += "<ss:Cell>" + Environment.NewLine;
            sheet += "<ss:Data ss:Type=\"String\">" + column + "</ss:Data>" + Environment.NewLine;
            sheet += "</ss:Cell>" + Environment.NewLine;
        }
        sheet += "</ss:Row>" + Environment.NewLine;
    }
    sheet += "</ss:Table>" + Environment.NewLine;
    sheet += "</ss:Worksheet>" + Environment.NewLine;
    sheet += "</ss:Workbook>" + Environment.NewLine;

    return Content(sheet);

If I put a breakpoint and copy the value of the sheet variable into notepad and save that locally on my machine as export.xml I can then open that file up fine and it has no issues.

The problem I have is that when I let this method in the controller continue running I get a prompt back in the browser to open an file, which is what I would expect, but when I click open, excel opens and then I get and error message. The error message that I get is

Microsoft Excel cannot open or save any more documents because there is not enough available memory or disk space.

What am I missing to make this controller pass in the correct information back to the browser.

来源:https://stackoverflow.com/questions/15691910/mvc-4-export-to-excel-failing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!