您尝试打开的文件与 Asp.Net 中文件扩展名指定的格式不同 [英] the file you are trying to open is in a different format than specified by the file extension in Asp.Net

查看:10
本文介绍了您尝试打开的文件与 Asp.Net 中文件扩展名指定的格式不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这是我的代码

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

}

当我尝试打开 Excel 时出现此错误

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

单击是"后,文件可以正常打开.但我不希望出现此消息.

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

推荐答案

我已经使用 CloseXML 解决了问题.

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();
}

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

Installed ClosedXML in my project using Nuget Package Manager.

这篇关于您尝试打开的文件与 Asp.Net 中文件扩展名指定的格式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆