You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#实现空单元格继承同列上值规则填充二维表格数组

C# 不规则HTML表格规整填充实现

原基础代码直接把所有单元格无差别追加到一维List<string>的写法存在硬伤:会完全丢失单元格所属的行、列位置信息,一旦出现行长度不一致、空白单元格的情况,根本无法定位单元格坐标,所以首先要调整采集阶段的逻辑,按行存储数据,再按规则填充。

核心实现逻辑

  • 采集阶段逐行遍历表格,每行的单元格单独存为一个集合,保留行级结构
  • 自动统计表格总行数、总列数:总列数取所有行中单元格数量的最大值,不需要硬编码表格尺寸
  • 空白单元格判定规则:匹配示例中的...标识、空字符串、仅含空白字符的内容
  • 填充规则:按列从上到下遍历,当前单元格为空白时,直接继承同列上方最近的非空单元格值;首行无上方值时空白保留为空即可

完整可运行代码

// 按行存储单元格数据,替代原来拍平的一维List
List<List<string>> rowData = new List<List<string>>();
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(myHtmlDoc);

// 逐行采集单元格,保留行列结构
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))
{
    var rows = table.SelectNodes("tr");
    if (rows == null) continue;
    
    foreach (HtmlNode row in rows)
    {
        List<string> currentRowCells = new List<string>();
        var cells = row.SelectNodes("th|td");
        if (cells != null)
        {
            foreach (HtmlNode cell in cells)
            {
                // 统一去除单元格内容首尾空白,避免多余空格影响判定
                string cellText = cell.InnerText.Trim();
                currentRowCells.Add(cellText);
            }
        }
        rowData.Add(currentRowCells);
    }
}

// 自动计算表格尺寸,无需硬编码行列数
int rowCount = rowData.Count;
int colCount = rowData.Max(r => r.Count);
string[,] DataArray = new string[rowCount, colCount];

// 填充二维数组+空白值继承
for (int colIndex = 0; colIndex < colCount; colIndex++) // 按列遍历,方便继承上方值
{
    for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) // 从上到下遍历当前列每一行
    {
        string currentValue = string.Empty;
        // 判断当前行的当前列是否存在有效非空白单元格
        if (colIndex < rowData[rowIndex].Count)
        {
            string rawValue = rowData[rowIndex][colIndex];
            // 非空白判定:不是...标识,不是空串,不是全空白字符
            if (!rawValue.Equals("...") && !string.IsNullOrWhiteSpace(rawValue))
            {
                currentValue = rawValue;
            }
        }

        // 当前值为空且不是首行,直接取同列上一行已填充的值(也就是上方最近的非空值)
        if (string.IsNullOrEmpty(currentValue) && rowIndex > 0)
        {
            currentValue = DataArray[rowIndex - 1, colIndex];
        }

        DataArray[rowIndex, colIndex] = currentValue;
    }
}

效果说明

针对任意列出现空白的测试用例,填充结果完全符合预期:

第一列第二列第三列
aaa123456
aaa123468
bbb507206
bbb450206

如果需要兼容HTML原生的rowspan、colspan跨行跨列属性,只需要在采集单元格阶段,根据属性值给对应行列补入占位单元格即可,后续填充逻辑不需要改动。

内容的提问来源于stack exchange,提问作者madalandria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 14:06:25