Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the file you are trying to open is in a different format than specified by the file extension in Asp.Net

the file you are trying to open is in a different format than specified by the file extension c# error when trying to open file in excel.

Here is my code

public ActionResult Export(string filterBy)
{
    MemoryStream output = new MemoryStream();
    StreamWriter writer = new StreamWriter(output, Encoding.UTF8);

    var data = City.GetAll().Select(o => new
    {
        CountryName = o.CountryName,
        StateName = o.StateName,
        o.City.Name,
        Title = o.City.STDCode
    }).ToList();
    var grid = new GridView { DataSource = data };
    grid.DataBind();
    var htw = new HtmlTextWriter(writer);

    grid.RenderControl(htw);

    writer.Flush();
    output.Position = 0;

    return File(output, "application/vnd.ms-excel", "test.xls");

}

when am trying to open excel i get this error

the file you are trying to open is in a different format than specified by the file extension

enter image description here

After clicking on Yes the file open properly. but i don't want this msg to appear.

like image 250
Rahul Rajput Avatar asked Apr 22 '13 10:04

Rahul Rajput


People also ask

How do you solve Excel Cannot open the file because the file format or file extension is not valid in C #?

Step 1: Launch Microsoft Excel on your PC. Step 2: Head to the “files” section, and click “Export.” Step 3: In the section, select “change file type” and click on the file with the error. Step 4: Change the file extension and save the file.


1 Answers

I have used CloseXML to solve the problem.

public static void ExportToExcel(IEnumerable<dynamic> data, string sheetName)
{
    XLWorkbook wb = new XLWorkbook();
    var ws = wb.Worksheets.Add(sheetName);
    ws.Cell(2, 1).InsertTable(data);
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    HttpContext.Current.Response.AddHeader("content-disposition", String.Format(@"attachment;filename={0}.xlsx",sheetName.Replace(" ","_")));

    using (MemoryStream memoryStream = new MemoryStream())
    {
        wb.SaveAs(memoryStream);
        memoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
        memoryStream.Close();
    }

    HttpContext.Current.Response.End();
}

Installed ClosedXML in my project using Nuget Package Manager.

like image 172
Rahul Rajput Avatar answered Oct 03 '22 04:10

Rahul Rajput