导出到 .xls 中的 excel 正在工作,但在更改内容类型后导出到 .xlsx 不起作用 - 我的代码如下:
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;
}
}