我创建了一个简单的应用程序,而将数据导出到Excel中。现在,数据已导出到Excel成功,但是当我打开下载的Excel时,它将显示格式的例外。
public ActionResult ExportOrder()
{
List<OrderItem> data = new List<OrderItem>();
GridView gv = new GridView();
gv.DataSource = data;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + Common.GenerateSerialNo() + ".xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("OrderProducts");
}
这是我在Excel打开时的格式问题。格式发行图像
请建议我解决这个问题。
我尝试了使用NPOI或其他付费工具的解决方案。我们可以在不使用任何第三方工具的情况下解决格式问题。我也尝试了一些解决方案,但对我不起作用。
您需要在执行导出时不在数据上设置样式
private void gvPrint_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
e.Row.Cells(0).Attributes.Add("class", "text");
e.Row.Cells(1).Attributes.Add("class", "text");
e.Row.Cells(2).Attributes.Add("class", "text");
e.Row.Cells(6).Attributes.Add("class", "text");
e.Row.Cells(7).Attributes.Add("class", "text");
e.Row.Cells(8).Attributes.Add("class", "text");
}
}