Expand HTML rowspan and colspan into a 2D Table Grid

When you are working with an HTML document that contains complex table headers, directly extracting<td>text often yields corrupted data. A setting withrowspan="

Tables with merged headers often break simple extraction. This guide is for developers and document processors who need a clean two-dimensional grid from HTML tables with rowspan and colspan cells.

Reading raw <td> text can silently corrupt your data. A cell with rowspan="3" is written once in the HTML but occupies three rows in the logical table. If your code assumes every row has the same number of columns, it may throw an index error or join data from the next row onto the current one. Malicious or damaged HTML can also declare a colspan="99999", which can exhaust memory if your script allocates space for it without checking.

You will learn how to expand merged cells into a grid with a state machine, how to design synthetic test cases that cover normal and boundary inputs, and how to add size checks to a Python example. You will also get an acceptance table for deciding when results need manual review.

How do you expand rowspan and colspan into a 2D grid? The short answer

Track which grid coordinates are already occupied by merged cells above, skip those positions, and fill every position a new cell's span covers, with explicit size checks throughout.

Your situationWhat to doWhy
Your table has rowspan or colspan cellsTrack occupied grid coordinates and fill every position a span coversReading <td> text directly leaves rows with mismatched lengths
Your HTML comes from untrusted or damaged sourcesSet a maximum grid size and validate spans before allocatingA huge colspan could exhaust memory
You want to check your logicTest with a small synthetic sample covering ordinary, colspan and rowspan cellsIt confirms the expansion logic for that input
Span values conflict or exceed the tableKeep the earlier cell, log the conflict, or raise a clear errorThis prevents silent corruption
Dirty data reaches productionApply the acceptance table and review flagged cases manuallyAutomatic rules cannot settle every case

Why does a merged cell break simple extraction?

A merged cell appears once in the DOM but takes up several grid positions. That gap between the markup and the logical table causes most of the problems.

The risk of a mismatched grid

  • Index errors: code that assumes equal row lengths can fail with an index-out-of-bounds exception.
  • Misaligned data: data from the next row can be concatenated onto the current row.
  • Hidden corruption: the program may keep running while the output is wrong.

The risk of oversized spans

  • Memory explosion: malicious or corrupted HTML might declare a colspan="99999". If the script blindly allocates memory for it, resources run out almost instantly.

How do you build the expanded grid?

The core approach is not to search for an off-the-shelf "table-to-CSV" function. Instead, maintain a state machine for a two-dimensional grid yourself.

  1. Scan the DOM rows one at a time.
  2. Keep track of the coordinates already occupied by merged cells from above.
  3. When you reach an occupied coordinate, skip it.
  4. When you reach a new cell, fill as many grid positions as its rowspan and colspan require.
  5. Check the size limits at every step, so your parser validates input rather than trusting it.

Designing synthetic samples and boundary cases

To verify the expansion logic, build a minimal but complete synthetic HTML sample. Do not base it on real business data. Design it to cover the critical paths.

A correct input with three typical cases

The correct input should include:

  • Ordinary cells
  • Horizontal merging with colspan
  • Vertical merging with rowspan

For example, in a 3-row-by-3-column logical table, the cell in row 1 has rowspan="2", and a cell in row 2 has colspan="2". The expected output is a standard two-dimensional list. Positions covered by a merge are filled with None or a specific placeholder, so row lengths stay consistent.

In this example:

  • The first column of row 2 repeats the value from row 1, because it is a rowspan continuation.
  • The second and third columns of row 2 contain their own values.
  • The first column of row 3 also continues the value from row 1.

Error and boundary inputs

Error and boundary inputs matter just as much. Consider these cases:

  • A declared colspan="10000" in a table with only 3 columns of data.
  • A rowspan larger than the actual number of rows.
  • Two cells whose spans overlap. This usually indicates an error in the HTML source.

Your code should neither crash nor silently accept these inputs. A reasonable strategy is to set a maximum grid threshold, such as 1000 by 1000. If the computed dimensions exceed it, either raise a clear exception or return partial results with a warning. For overlapping spans, you can keep the earlier cell, ignore the later illegal overwrite, and log the coordinate conflict.

Python implementation with protection

The example below uses BeautifulSoup to parse HTML and expand the table. It does not depend on any third-party table-specific library. It relies entirely on DOM traversal and coordinate state management.

Lock the version of beautifulsoup4 before you run it. The example uses only an in-memory HTML string. To process external files, read the file contents into a string variable first and pass that string in.

from bs4 import BeautifulSoup

def expand_html_table(html_content, max_rows=1000, max_cols=1000):
    """
    将含rowspan/colspan的HTML表格展开为二维列表。
    包含网格尺寸防护,防止恶意或错误标签导致内存溢出。
    """
    soup = BeautifulSoup(html_content, 'html.parser')
    table = soup.find('table')
    if not table:
        return []

    grid = []
    rows = table.find_all('tr')

    for r_idx, tr in enumerate(rows):
        if r_idx >= max_rows:
            raise ValueError(f"表格行数超过安全上限 {max_rows}")

        # 确保当前行存在
        while len(grid) <= r_idx:
            grid.append([])

        c_idx = 0
        cells = tr.find_all(['td', 'th'])

        for cell in cells:
            # 找到下一个未被占用的列位置
            while c_idx < len(grid[r_idx]) and grid[r_idx][c_idx] is not None:
                c_idx += 1

            # 防御性解析:非数字属性默认为1
            try:
                colspan = int(cell.get('colspan', 1))
                rowspan = int(cell.get('rowspan', 1))
            except (ValueError, TypeError):
                colspan, rowspan = 1, 1

            text = cell.get_text(strip=True)

            # 安全检查:防止单个单元格撑爆网格
            if c_idx + colspan > max_cols or r_idx + rowspan > max_rows:
                raise ValueError(
                    f"单元格跨度({rowspan}x{colspan})在位置({r_idx},{c_idx})"
                    f"超出安全网格{max_rows}x{max_cols}"
                )

            # 填充所有被该单元格覆盖的坐标
            for i in range(rowspan):
                target_row = r_idx + i
                while len(grid) <= target_row:
                    grid.append([])
                for j in range(colspan):
                    target_col = c_idx + j
                    while len(grid[target_row]) <= target_col:
                        grid[target_row].append(None)
                    # 仅当目标位置为空时才写入(处理冲突)
                    if grid[target_row][target_col] is None:
                        grid[target_row][target_col] = text

            c_idx += colspan

    return grid

# 合成测试用例(仅用于验证逻辑,非生产实测)
TEST_HTML = """
<table>
  <tr><td rowspan="2">A</td><td>B</td><td>C</td></tr>
  <tr><td colspan="2">D</td></tr>
  <tr><td>E</td><td>F</td><td>G</td></tr>
</table>
"""

result = expand_html_table(TEST_HTML)
assert result == [
    ['A', 'B', 'C'],
    ['A', 'D', 'D'],
    ['E', 'F', 'G']
], f"展开结果不符合预期: {result}"

The key to this code is its two-layer safeguard:

  • The outer loop checks the total number of rows.
  • The inner loop checks, before filling a cell, whether that cell's span would push the grid past its bounds.

Because while expands rows and columns as needed, the code avoids the risk of pre-allocating very large arrays. The assertions verify the expected output for the synthetic example. They confirm the logic for this input only. They do not show that the implementation has been tested on a wide range of real documents.

Acceptance criteria and manual review thresholds

Code that passes the synthetic example may still fail on dirty data in production. The table below lists common observations from real document processing, the automatic decision for each, and the cases that need manual review.

ObservationAutomatic decisionCases requiring manual review
The rowspan/colspan value is a non-numeric stringTreat it as 1 and log a warningFrequent problems in the same table may point to OCR errors or template corruption
A cell span causes inconsistent logical column countsUse the maximum column count and pad short rows with NoneThe column count differs from the expected range (for example, by more than 30%), which may mean the structure is corrupted
A nested table (a table inside a td)Expand the outer table and leave the inner HTML intactBusiness meaning depends on the nested content, so you need a custom recursive strategy
The grid reaches the safety thresholdRaise an exception and refuse to process the tableAfter confirming a legitimate oversized table rather than malicious input, adjust the parameters and retry
A merged cell's text contains newline charactersKeep the original line breaksWhether a newline is layout noise or a structured delimiter depends on context

The code demonstration checks only coordinate expansion. Real acceptance testing means comparing the output with the original document's visual layout, to confirm that key data points were not lost or misaligned during conversion.

References and next steps

Next steps: Run the code above on your own HTML sample, and record the types and frequencies of the exceptions it raises.

Checking translated documents with a checklist

Process the body text, links, code, and structure of a web document separately. Include the protected sections in your acceptance checklist, then check the readability and page display after translation.

OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation. For the table data alone, OmniDoc's free extraction finds each table's header and cells in PDFs and scans and writes them out as Markdown tables and JSON; common merged headers are recognized.

🎯 Which approach fits you?

If you are processing a synthetic test case

Build a small sample with ordinary, colspan and rowspan cells, and check the expanded grid against the expected output.

If you are reading external files

Read the file into a string variable first, then pass the string to the parser, as the note above describes.

If you are concerned about untrusted HTML

Set a maximum grid size and reject or log tables that exceed it before allocating memory.

❓ FAQ

1. Why can't I just read the <td> text directly?

A cell with rowspan or colspan appears once in the HTML but occupies several grid positions. Reading the text directly can leave rows with different lengths, which causes errors or misaligned data.

2. How do I stop a malicious colspan from exhausting memory?

Set a maximum grid threshold, such as 1000 by 1000. If the computed size exceeds it, raise a clear exception or return partial results with a warning.

3. What should happen when two spans overlap?

Keep the earlier cell, ignore the later overwrite, and log the coordinate conflict. Overlaps usually point to an error in the HTML source.

4. Does passing the synthetic test mean my code is ready for production?

No. The assertions confirm the logic for that input only. Test on your own samples and apply the acceptance table to flagged cases.

📝 Summary

Expanding rowspan and colspan into a two-dimensional grid keeps your data aligned and your parser safe. Test the logic with synthetic samples, add size checks, and review flagged cases before you rely on the output.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-29