【问题标题】:Asp.net gridview export to excel formatting issueAsp.net gridview 导出到 excel 格式问题
【发布时间】:2016-12-02 11:43:14
【问题描述】:

我创建了一个简单的应用程序,同时将数据导出到 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 中打开时出现的格式问题。 Format Issue Image

请建议我解决这个问题。

我尝试过但找到了使用 NPOI 或其他付费工具的解决方案。我们可以在不使用任何第三方工具的情况下解决格式化问题吗?我也尝试了一些解决方案,但对我不起作用。

【问题讨论】:

  • 联系号码列List的数据类型是什么?
  • OrderItem.Contact_No的类型是什么?
  • 开始使用专门的库来创建 Excel 文件,例如 EPPlus。您现在所做的只是创建一个扩展名为 .xls 的 HTML 页面。

标签: c# asp.net asp.net-mvc gridview


【解决方案1】:

导出时需要在数据绑定上设置样式,如下所示

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");
    }
}

【讨论】:

  • 您好,我没有在代码中使用任何 gridview。我正在制作一个关于导出时间的网格视图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-24
相关资源
最近更新 更多