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

问题描述 投票:0回答:2

我想将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>
c# asp.net html-parsing html-agility-pack
2个回答
1
投票

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

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


0
投票

是的,你不能在csv格式中放入rowspan或colspan,对我有用的是在空格应该存在的地方放置空格

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

"";SEPTIEMBRE;;OCTUBRE;;NOVIEMBRE;;TOTAL;
PRODUCTOS;cantidad;monto;cantidad;monto;cantidad;monto;cantidad;monto
© www.soinside.com 2019 - 2024. All rights reserved.