简体   繁体   中英

Export expandable table to CSV using Javascript

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>

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

Update: the table looks like this: 在此处输入图片说明

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.

See the code below.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM