ASP.net Gridview导出到Excel .xlsx不工作

导出到Excel中的.xls正在工作,但导出到.xlsx不工作后,更改内容types – 我的代码如下:

private void ExportToExcel() { try { Response.Clear(); Response.Buffer = true; //Response.AddHeader("content-disposition", "attachment;filename=LoanDataDeletion.xls"); //Response.Charset = ""; // Response.ContentType = "application/vnd.ms-excel"; Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.Charset = ""; Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", "LoanDataDeletion.xlsx")); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); grdView.AllowPaging = false; grdView.DataBind(); //Change the Header Row back to white color grdView.HeaderRow.Style.Add("background-color", "#FFFFFF"); //Apply style to Individual Cells for (int i = 0; i < grdView.Columns.Count; i++) { grdView.HeaderRow.Cells[i].Style.Add("background-color", "green"); } for (int i = 0; i < grdView.Rows.Count; i++) { GridViewRow row = grdView.Rows[i]; //Change Color back to white row.BackColor = System.Drawing.Color.White; //Apply text style to each Row row.Attributes.Add("class", "textmode"); //Apply style to Individual Cells of Alternating Row if (i % 2 != 0) { row.Cells[0].Style.Add("background-color", "#C2D69B"); row.Cells[1].Style.Add("background-color", "#C2D69B"); row.Cells[2].Style.Add("background-color", "#C2D69B"); row.Cells[3].Style.Add("background-color", "#C2D69B"); } } grdView.RenderControl(hw); //style to format numbers to string string style = @"<style> .textmode { mso-number-format:\@; } </style>"; Response.Write(style); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); } catch (Exception) { throw; } } 

我想你得到的错误是“你试图打开的文件是在不同于文件扩展名指定的格式”。 发生这种情况的原因是,在传统的“导出到Excel”方法中,首先将GridView转换为HTMLstring,然后将该HTMLstring导出到Excel,但Excel 2007/2010无法识别纯html格式。 有一种方法可以在不使用HtmlTextWriter的情况下使用EPPlus 。 它允许您在服务器上创buildExcel电子表格。 检查这篇文章: 在asp.net或这一个创buildExcel工作簿 : 导出Gridview数据到Excel(.xlsx),而不使用Asp.NET中的HtmlTextWriter

  string path = System.IO.Path.GetTempPath() + System.DateTime.Now.Ticks + ".xls"; GridView grdTemp = new GridView(); grdTemp.DataSource = dt; grdTemp.Caption = "Products<br> " + DateTime.Now; grdTemp.DataBind(); using (StreamWriter sw = new StreamWriter(path)) { using (HtmlTextWriter hw = new HtmlTextWriter(sw)) { grdTemp.RenderControl(hw); } } string save_path = path; Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", System.DateTime.Now.Ticks + ".xls")); Response.ContentType = "application/excel"; Response.WriteFile(save_path); Response.End(); System.IO.File.Delete(save_path);