【问题标题】:Export html page with data(Grid view) and images to excel in Asp.net C#在 Asp.net C# 中将带有数据(网格视图)和图像的 html 页面导出为 excel
【发布时间】:2018-09-27 13:47:35
【问题描述】:

标题可能无法很好地描述我的要求, 实际上我正在寻找一些指导方针来解决我的代码问题,

我正在创建一个应用程序,它将导出包含数据的 HTML 页面 网格视图和徽标图像到 excel。到目前为止我在下面做了什么:

private void ExportExcel()
    {
        //This method is defined in ButtonClick Event
        Response.Clear();
        Response.Buffer = true;
        Response.ClearContent();
        Response.ClearHeaders();
        Response.Charset = "";
        GridView2.AllowPaging = false;
        string FileName = "Exported" + DateTime.Now + ".xls";
        StringWriter strwritter = new StringWriter();
        HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
        this.EnableViewState = false;
        GridView2.DataBind();
        Response.Write(ExportDiv.InnerHtml);
        GridView2.GridLines = System.Web.UI.WebControls.GridLines.Both;
        GridView2.HeaderStyle.Font.Bold = true;
        GridView2.RenderControl(htmltextwrtter);
        Response.Write(strwritter.ToString());
        Response.End();
    }

上面的代码工作正常,但他们的问题是标志图像附加图像显示标志图像问题, Check Image here

徽标图像未设置在我实际需要的单元格内。我什么 需要在这张照片中显示Please check image

【问题讨论】:

  • 我不能直接添加图片请编辑我的问题添加图片..
  • 开始使用专门的库来创建 Excel 文件,例如 EPPlus。您现在所做的只是创建一个扩展名为 .xls 的 HTML 页面。
  • PS 你从哪里得到那段代码以使用HtmlTextWriter 导出到 Excel?
  • 我不能使用库,
  • @VDWWD 你检查过我要什么吗?

标签: c# asp.net excel


【解决方案1】:

无需使用任何外包库,您就可以做到这一点,这会导致网格视图和 HTML 代码的对齐问题。

所以我所做的是创建一个 div 并将其命名为 ExportDiv 并添加 ExportDiv 里面的 HTML 表,然后我在里面写我的 HTML 代码 通过一次又一次地添加行和列来创建表格,并添加网格视图 在我的 Table 里面,它是在 ExportDiv 里面创建的。

以下是点击事件背后的代码。

 private void ExportToExcel(string strFileName)
    {
        StringBuilder sb = new StringBuilder();
        string attachment = "attachment; filename=" + strFileName;
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/vnd.ms-excel";
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        StringWriter oStringWriter = new StringWriter();
        HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);
        Response.Output.Write(sb.ToString());
        GridView3.AllowPaging = false;
        GridView3.DataBind();
        ExportDiv.RenderControl(oHtmlTextWriter);
        string style = @"<style> TD { mso-number-format:\@; } </style>";
        Response.Output.Write(oStringWriter.ToString());
        Response.Write(style);
        Response.End();
    }

上述代码的好处是它相应地设置了 HTML 设计和网格视图对齐。

其他在此类工作中遇到问题的人可以在 cmets 中提问 一定要帮助他。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多