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

在JavaScript中如何遍历含嵌套行的表格并生成CSV?

嵌套表格导出CSV问题

问题描述

需要遍历包含嵌套行的表格,将所有数据导出为CSV格式。数据分为两层结构:

  • 个人档案(Profile)
  • 个人档案 > 关联用户(Linked users)
    数据来自API返回的嵌套对象数组,已完成视图渲染。

现有问题

当前导出逻辑仅部分生效,会将包含嵌套行的表格行识别为合并行,无法排除该类行,导致输出结果不符合预期:

当前输出

  • Tom
  • Tom Jack Sam Alex(合并行内容)
  • Jack
  • Sam
  • Alex
  • Josh

期望输出

  • Tom
  • Jack
  • Sam
  • Alex
  • Josh

表格结构与代码示例

JavaScript 导出逻辑

/*
 ** Export table data to CSV
 */
function exportToCsv() {
  // 获取表格元素
  var table = document.querySelector('table')

  // 创建存储单元格值的空数组
  var cellValues = []

  // 获取表头数据
  var headerValues = []
  table.querySelectorAll('thead th').forEach(function(header) {
    headerValues.push(header.textContent.trim())
  })

  // 将表头加入结果数组
  cellValues.push(headerValues.join(','));

  // 递归处理表格行的函数
  function processRows(rows) {
    rows.forEach(function(row) {
      var rowValues = []

      // 检查当前行是否包含嵌套表格
      var nestedTables = row.querySelectorAll('table');

      if (nestedTables.length > 0) {
        // 递归处理嵌套表格的行
        nestedTables.forEach(function(nestedTable) {
          var nestedRows = nestedTable.querySelectorAll('tr')
          console.log(nestedRows[0].innerText)
          console.log(nestedRows[1].innerText)
          console.log(nestedRows[2].innerText)
          processRows(nestedRows)
        });
      } else {
        // 遍历当前行的单元格并收集值
        row.querySelectorAll('td').forEach(function(cell) {
          rowValues.push(cell.textContent.trim())
        });

        // 将当前行数据加入结果数组
        cellValues.push(rowValues.join(','))
      }
    })
  }

  // 处理顶层表格的行
  var topRows = table.querySelectorAll('tbody tr')
  processRows(topRows)

  // 在控制台打印CSV内容
  console.log(cellValues.join('\n'))

  // 拼接CSV数据(原代码存在变量未定义问题:csv_data未初始化)
  csv_data = csv_data.join('\n')

  // 调用下载函数
  downloadCsv(csv_data)
}

/*
 ** 下载CSV文件
 */
function downloadCsv(csv_data) {
  // 创建CSV Blob对象
  csv_data = new Blob([csv_data], {
    type: "text/csv"
  })

  // 创建临时下载链接
  const temp_link = document.createElement('a')
  temp_link.download = "GfG.csv"
  const url = window.URL.createObjectURL(csv_data)
  temp_link.href = url

  // 隐藏链接并触发下载
  temp_link.style.display = "none"
  document.body.appendChild(temp_link)
  temp_link.click()
  document.body.removeChild(temp_link)
}

HTML 表格结构

<table border="1" cellspacing="0" cellpadding="10">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Town</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Tom</td>
      <td>20</td>
      <td>London</td>
    </tr>
    <tr>
      <td colspan="3">
        <table>
          <tbody>
            <tr>
              <td>Jack</td>
              <td>30</td>
              <td>Glasgow</td>
            </tr>
          </tbody>
          <tbody>
            <tr>
              <td>Sam</td>
              <td>40</td>
              <td>Belfast</td>
            </tr>
            <tr>
              <td>Alex</td>
              <td>50</td>
              <td>Hull</td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
    <tr>
      <td>Josh</td>
      <td>20</td>
      <td>Cardiff</td>
    </tr>
  </tbody>
</table>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 13:24:50