Skip to content
Advertisement

display csv file inside a table using javascript

I have this script that gets the csv file, and separates it by column. 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.

<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:

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. My only problem is trying to get them inside a table using 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>

Advertisement

Answer

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.

Advertisement