简体   繁体   中英

ASP.NET MVC Excel export file format error

I am currently writing an ASP.NET MVC 5 controller action to export some data to an Excel file (using some code I found here). It works...mostly. It outputs an Excel file, which I can open, but not before displaying the following error message:

"The file format and extension of 'Export.xls' don't match. The file could be corrupted or unsafe. Unless you trust it's source, don't open it. Do you want to open it anyway?"

I go on to select "Yes" and then it opens. I can resave it on my machine and open that file and I don't get the error. It otherwise works fine, the only other oddness is that the file's gridlines are formatted differently than is usual for an Excel file, almost more like an HTML table than an Excel sheet. However, the weird error message isn't something that would be acceptable here, so I have to fix it.

Here is my code:

public void ExportExcel()
{
    // DataObject is a class that fetches the data for this method
    DataObject dataObj = new DataObject();
    var grid = new GridView();

    // dataObj.GetDataList returns a List<T> of data model class objects
    grid.DataSource = dataObj.GetDataList();
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=Export.xls");
    Response.ContentType = "application/vnd.ms-excel";
    Response.Charset = "";

    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);

    Response.Write(sr.ReadToEnd());
    Response.End();

}

I have already tried setting the Response.ContentType to other values ("application/excel", "application/ms-excel"), to no avail. I'm a little new to ASP.NET and C# in general, so there might be something I'm missing or doing wrong here; I'm more used to PHP and Zend. Any insight or help you could give would be greatly appreciated; thanks!

You're writing an HTML table as an Excel file. Basically, you're taking text with this:

<table>
    <tr>
        <td>
            Stuff
       </td>
    </tr>
</table>

and writing it as a text file with a .xls extension. Excel is "smart" enough (if you can call it that) to open the file and display it properly, although it alerts you that the file isn't actually an xls file first.

You need to either deal with it (not a good solution), convert the data in the table to a csv and send a CSV (a much better solution) or use an Excel library to create an actual Excel file and send that. Of those, the CSV is probably the easiest.

i got the same error. So, I started (using Microsoft.Office.Interop.Excel) get it from Nuget Manager.

Here is the code

 Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();

 Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
                Worksheet ws = (Worksheet)xla.ActiveSheet;       

/*Headers here */

   ws.Cells[1, 1] = "Header1";
            ws.Cells[1, 2] = "Header2"; ws.Cells[1, 3] = "Header3"; ws.Cells[1, 4] = "Header4"; ws.Cells[1, 5] = "Header5";

            int i = 2;

/* use your list here to fill the data rows */

            foreach (var a in pavmm.Funds)
            {
                ws.Cells[i, 1] = a.FilingID;
                ws.Cells[i, 2] = a.Security_Name; ws.Cells[i, 3] = a.Filing_Type; ws.Cells[i, 4] = a.st_name; ws.Cells[i, 5] = a.Permit;

                i = i + 1;
            }
            ws.Columns.AutoFit();
            ws.Rows.AutoFit();


        string folder = NewFolderName + "\\";
            if (!Directory.Exists(folder))
                Directory.CreateDirectory(folder);


            string filename =  ExcelsheetName + ".xlsx";
            filename = filename.Replace('/', '-');
            filename = filename.Replace('\\', '-');
            string path = Path.Combine(folder, filename);
            wb.SaveCopyAs(path);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM