我有以下代码将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?