简体   繁体   English

使用javascript在表格中显示csv文件

[英]display csv file inside a table using javascript

I have this script that gets the csv file, and separates it by column.我有这个脚本来获取 csv 文件,并按列分隔它。 I am having trouble to display the values in a table.我无法在表格中显示值。 I can't seem to get each column to create a new table row.我似乎无法让每一列创建一个新的表格行。 Any help will be appreciated as I am not very good at JS.任何帮助将不胜感激,因为我不太擅长 JS。

<script>
      getData();

      async function getData() {
        const response = await fetch('data.csv')
        const data = await response.text();
        console.log(data);


        const table = data.split('\n');
        table.forEach(row => {
          const columns = row.split(',')
          const date = columns[0]
          const temp = columns[1]

          console.log(date, temp);
        })

      }
    </script>

The data.csv looks something like this: data.csv 看起来像这样:

17-10-2020,25
17-10-2020,25
17-10-2020,25
17-10-2020,25
17-10-2020,25
17-10-2020,25
17-10-2020,25
17-10-2020,25

The console.log(data, temp) returns without the commas. console.log(data, temp) 返回时不带逗号。 My only problem is trying to get them inside a table using Javascript.我唯一的问题是尝试使用 Javascript 将它们放入表格中。

<table class="table text-left mt-2" id="data">
          <thead class="thead-dark">
            <tr>
              <th scope="col">#</th>
              <th scope="col">Date/Time</th>
              <th scope="col">Temperature</th>
            </tr>
          </thead>
          <tbody>
            <!-- Generate the csv table rows here -->
          </tbody>
</table>

 const tableBody = document.getElementById("table-body"); getData(); async function getData() { const response = await fetch('data.csv') const data = await response.text(); console.log(data); const table = data.split('\\n'); table.forEach((row,index) => { const columns = row.split(',') const date = columns[0] const temp = columns[1] console.log(date, temp); const tr = document.createElement("tr"); tr.innerHTML = ` <td>${index + 1}</td> <td>${date}</td> <td>${temp}</td> `; // finally add the <tr> to the <tbody> tableBody.append(tr); }) }
 <table class="table text-left mt-2" id="data"> <thead class="thead-dark"> <tr> <th scope="col">#</th> <th scope="col">Date/Time</th> <th scope="col">Temperature</th> </tr> </thead> <tbody id='table-body'> <!-- Generate the csv table rows here --> </tbody> </table>

Try this and let me know if its working or not.试试这个,让我知道它是否有效。 Please note i've added an ID to the table body and selecting that via ID.请注意,我已在表格正文中添加了一个 ID,并通过 ID 选择了该 ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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