MVC 4 Export to Excel

I have the following code in the controller 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 it locally on my computer as export.xml, I can open this file in order and not have problems.

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

Microsoft Excel cannot open or save any documents because there is not enough free space on the disk or disk.

What I miss is for this controller to pass the correct information back to the browser.

0
source share

Source: https://habr.com/ru/post/954314/


All Articles