您尝试打开的文件格式与Asp.Net中文件扩展名指定的格式不同

Rah*_*put 18 excel export-to-excel c#-4.0 asp.net-mvc-4

尝试在excel中打开文件时,您尝试打开的文件格式与文件扩展名c#error指定的格式不同.

这是我的代码

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");

}
Run Code Online (Sandbox Code Playgroud)

当我试图打开excel时,我得到了这个错误

您尝试打开的文件格式与文件扩展名指定的格式不同

在此输入图像描述

单击是后,文件正常打开.但我不希望这个消息出现.

Rah*_*put 23

我使用CloseXML来解决问题.

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();
}
Run Code Online (Sandbox Code Playgroud)

使用Nuget Package Manager在我的项目中安装ClosedXML .


von*_* v. 5

您尝试打开的文件格式与文件扩展名指定的格式不同

您不断收到该警告消息,因为创建的文件不是实际的Excel文件.如果你要查看生成的文件,它只是一堆html标签.请记住,一个GridViewRenderControl将生成一个html表.

要解决您的问题,您需要使用第三方工具创建一个真正的Excel文件(您可能想要使用的一个工具是NPOI)或创建一个逗号分隔文件,或只是一个csv文件,并返回该文件.