繁体   English   中英

使用 C# 将 HTML 字符串导出到 ASP.Net 中的 Excel 文件

[英]Export HTML string to Excel file in ASP.Net using C#

我在数据库MySql version 8.0.17中有这张表,其中包含有关字段contents的 HTML 代码

<p><h3><span style=color:#0000ff;><strong>test</strong></span></h3></p>
<h4><strong>- test1</strong></h4>
<h4><strong>- test2</strong></h4>

我不是数据库管理员,所以我只能从无法修改的表中读取..

在 xls 文件上以 excel 格式导出此表时,找到所有 HTML 标记

在此处输入图像描述

如何解决这个问题?

提前感谢您的帮助。

我的代码如下

private void MTxlssp()
{
    MySqlCommand cmd =
        new MySqlCommand("SP");

    DataTable dt = GetData(cmd);
    GridView GridView1 = new GridView
    {
        AllowPaging = false,
        DataSource = dt
    };

    GridView1.DataBind();

    Thread.Sleep(3000);
    Response.Clear();
    Response.Buffer = true;

    Response.AddHeader("content-disposition", attachment;filename=\"test.xls\"");

    Response.ContentEncoding = Encoding.UTF8;
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";

    HttpCookie cookie2 = new HttpCookie("ExcelDownloadFlag")
    {
        Value = "Flag",
        Expires = DateTime.Now.AddDays(1)
    };
    Response.AppendCookie(cookie2);

    using (StringWriter sw = new StringWriter())
    {
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        GridView1.HeaderRow.BackColor = Color.White;

        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            cell.BackColor = GridView1.HeaderStyle.BackColor;
        }
        foreach (GridViewRow row in GridView1.Rows)
        {
            row.BackColor = Color.White;
            foreach (TableCell cell in row.Cells)
            {
                if (row.RowIndex % 2 == 0)
                {
                    cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                }
                else
                {
                    cell.BackColor = GridView1.RowStyle.BackColor;
                }
                cell.CssClass = "textmode";
            }
        }

        GridView1.RenderControl(hw);
        string style = @"<style> .textmode { } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
}

如果它只是您需要的显示文本,那么 Nuglify 库可能会帮助您。 它支持从 HTML 中提取文本:

var html = @"<p><h3><span style=color:#0000ff;><strong>test</strong></span></h3></p>
<h4><strong>- test1</strong></h4>
<h4><strong>- test2</strong></h4>";

var result = Uglify.HtmlToText(html);

Console.WriteLine(result.Code);  

你可以从这里下载它: https://github.com/trullock/NUglify或从 Nuget 获取。

我刚刚在您的 html 样本上运行它,它会产生:

 test - test1 - test2 

根据您对@Ivan Khorin 的评论,我假设这就是您想要的

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM