你试图打开该文件是不同的格式不是由Asp.Net文件扩展名指定 [英] the file you are trying to open is in a different format than specified by the file extension in Asp.Net
本文介绍了你试图打开该文件是不同的格式不是由Asp.Net文件扩展名指定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您正试图打开该文件是不是由文件扩展名的C#错误试图在Excel中打开文件时,指定不同的格式。
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.
下面是我的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");
}
当我试图打开的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包管理器我的项目安装ClosedXML。
Installed ClosedXML in my project using Nuget Package Manager.
这篇关于你试图打开该文件是不同的格式不是由Asp.Net文件扩展名指定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文