数据表导出为ex​​cel工作为“.xls”格式但给出“.xlsx”格式错误

时间:2017-09-12 13:08:20

标签: c# asp.net excel export-to-excel

我有以下代码将DataTable下载为excel文件。如果我以“.xls”格式下载,此代码正常工作,但如果我以“.xlsx”格式下载,则无效。

var filename = "Students.xlsx";
var sw = new System.IO.StringWriter();
var hw = new System.Web.UI.HtmlTextWriter(sw);
var grid = new System.Web.UI.WebControls.DataGrid();
grid.DataSource = dt;
grid.DataBind();

//customizing format
grid.HeaderStyle.BackColor = System.Drawing.Color.LightGray;
grid.HeaderStyle.Font.Bold = true; 
grid.RenderControl(hw);

//string style = @"<style> .textmode { mso-number-format:\@; } </style>";

Response.Clear();
Response.Buffer = true;
//Response.ContentType = "application/vnd.ms-excel";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.Write(sw.ToString());
Response.Flush();
Response.End();

如果我以“.xlsx”格式下载,则会出现以下错误,无法打开excel文件。如何以“.xlsx”格式下载excel?

enter image description here

0 个答案:

没有答案