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 .
| 归档时间: |
|
| 查看次数: |
66883 次 |
| 最近记录: |