使用Java脚本将可扩展表导出为CSV [英] Export expandable table to CSV using Javascript

查看:66
本文介绍了使用Java脚本将可扩展表导出为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML中有一个可扩展表:

There is an expandable table in HTML:

<table width="900" id="mytable">
      <tr>
        <th>Cost Category</th>
        <th>Costs</th>
      </tr>
<tr data-depth="0" class="collapse level0" bgcolor="#A2D9CE">
    <td><span class="toggle collapse"></span> First row</td>
    <td>500</td>
</tr>
<tr data-depth="1" class="collapse level1" bgcolor="#D5F5E3">
    <td><span class="toggle"></span> Second row</td>
    <td>300</td>
</tr>
<tr data-depth="2" class="collapse level2" bgcolor="#D6EAF8">
    <td><span class="toggle"></span> Third row</td>
    <td>250</td>
</tr>
</table>

如何在保持结构可扩展表的同时将其导出为CSV?

How can I export it to CSV while keeping the structure--expandable table?

更新:该表如下所示:

Update: the table looks like this:

推荐答案

要在CSV中表示此表数据,除了CSV中的费用类别"和费用"列外,您还需要深度"列

To represent this table data in a CSV, you will need a "Depth" column in addition to the "Cost Category" and "Cost" columns in the CSV.

请参见下面的代码.

const csv = [];
$("#mytable").find("tr").each((index, row) => {
  const category = $(row).find("th,td").eq(0).text().trim();
  const cost = $(row).find("th,td").eq(1).text().trim();
  const depth = $(row).data("depth") || (index === 0 ? "Depth" : 0);
  csv.push([category, cost, depth].join(", "));
});
console.log(csv.join("\n"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table width="900" id="mytable">
  <tr>
    <th>Cost Category</th>
    <th>Costs</th>
  </tr>
  <tr data-depth="0" class="collapse level0" bgcolor="#A2D9CE">
    <td><span class="toggle collapse"></span> First row</td>
    <td>500</td>
  </tr>
  <tr data-depth="1" class="collapse level1" bgcolor="#D5F5E3">
    <td><span class="toggle"></span> Second row</td>
    <td>300</td>
  </tr>
  <tr data-depth="2" class="collapse level2" bgcolor="#D6EAF8">
    <td><span class="toggle"></span> Third row</td>
    <td>250</td>
  </tr>
</table>

这篇关于使用Java脚本将可扩展表导出为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆