将HTML表解析为CSV文件(colspan和rowspan)

时间:2014-07-11 11:12:47

标签: c# asp.net html-parsing html-agility-pack

我想将HTML表解析为CSV文件,但保留正确的colspan和rowpspan数。

我正在使用“;”作为分隔符单元格。因此,当有2列的colspan时,例如,它不会只有一个“;”,它将有2个。

我可以提取表的内容并在 tr 指标结束时换行,但不知道如何处理 colspan rowspan

HtmlNodeCollection rows = tables[0].SelectNodes("tr");

// Aux vars
int i;
// ncolspan

// For each row...
for (i = 0; i < rows.Count; ++i)
{
    // For each cell in the col...
    foreach (HtmlNode cell in rows[i].SelectNodes("th|td"))
    {
        /* Unsuccessful attempt to treat colspan
        foreach (HtmlNode n_cell in rows[i].SelectNodes("//td[@colspan]"))
        {
            ncolspan = n_cell.Attributes["colspan"].Value;
        }
        */

        text.Write(System.Text.RegularExpressions.Regex.Replace(cell.InnerText, @"\s\s+", ""));
        text.Write(";");
        /*
        for (int x = 0; x <= int.Parse(ncolspan); x++)
        {
            text.Write(";");
        }
        */
    }
    text.WriteLine();
    ncolspan = "0";
}

请帮忙吗?谢谢!

更新:这是一个简单的示例表:

<table id="T123" border="1">
    <tr>
        <td colspan="3"><center><font color="red">Title</font></center></td>
    </tr>
    <tr>
        <th>R1 C1</th>
        <th>R1 C2</th>
        <th>R1 C3</th>
    </tr>
    <tr>
        <td>R2 C1</td>
        <td>R2 C2</td>
        <td>R2 C3</td>
    </tr>
    <tr>
        <td colspan="2">R3 C1 e C2 with "</td>
        <td>R3 C3</td>
    </tr>
    <tr>
        <td>R4 C1</td>
        <td colspan=2>R4 C2 e C3 without "</td>
    </tr>
    <tr>
        <td>R5 C1</td>
        <td>R5 C2</td>
        <td>R5 C3</td>
    </tr>
    <tr>
        <td rowspan ="2">R6/R7 C1: Two lines rowspan. Must leave the second line blank.</td>
        <td>R6 C2</td>
        <td>R6 C3</td>
    </tr>
    <tr>
        <td>R7 C2</td>
        <td>R7 C3</td>
    </tr>
    <tr>
        <td>End</td>
    </tr>
</table>

2 个答案:

答案 0 :(得分:1)

CSV不处理rowspan或colspan值 - 它是一种非常简单的格式,除了它的分隔符和行尾字符之外没有列或行的概念。

如果你想尝试保留rowspan和colspan,你需要使用一个中间对象模型,你可以用它来存储一个单元格的特定内容和它的位置,例如,在导出模型之前CSV。即使这样,CSV格式也不会像你希望的那样保留colspan和rowspan(就像Excel表格一样)。

答案 1 :(得分:0)

是真的,你不能把csv格式的rowpan或colspan放在哪里,对我有用的是把空格放在跨度应该存在的地方

这不是最好的选择,但在美学上它看起来很相似

"";SEPTIEMBRE;;OCTUBRE;;NOVIEMBRE;;TOTAL;
PRODUCTOS;cantidad;monto;cantidad;monto;cantidad;monto;cantidad;monto