DEV Community

Cover image for CSV-File to HTML <table>
Frank Wisniewski
Frank Wisniewski

Posted on

CSV-File to HTML <table>

it only takes a few lines of code

I have an Excel generated CSV file with some events...

Date;Event;Location
22.02.2022;Carnival Parade;Cologne
23.02.2022;Yoga for Wimps;Gran Canaria
25.02.2022;Melee fighting for tough guys;Moscow
26.02.2022;Binge Drinking;Munich
Enter fullscreen mode Exit fullscreen mode

... which I would like to display within a table element.

table Element

take the file from data Attribute...

<!DOCTYPE html>
<html lang=de>
  <meta charset=UTF-8>
  <title>CSV2Table</title>
  <link rel=stylesheet 
   href="https://unpkg.com/@picocss/pico@latest/css/pico.min.css">
  <div class=container >
    <h1>CSV File to Table</h1>
    <h3>Events for February</h3>
    <table data-csv=events.csv></table>
  </div>
  <script>
  const CsvToTable = async (tableElement) => {
    try {        
        const req = await fetch(tableElement.dataset.csv, {
          method: 'get',
          headers: {
            'content-type': 'text/csv;charset=UTF-8'}
        });
        if (req.status === 200) {
          const csv = await req.text();
          let myTableArray = csv.split('\n')
          let myTable=`<thead><tr><th>
           ${myTableArray[0].replaceAll(';',
          '<th>')}</tr></thead><tbody>`
          myTableArray.shift()
          myTableArray.forEach((aktRow) => {
          myTable+=`<tr><td>${aktRow.replaceAll(
          ';','<td>')}</tr></tbody>`})
          document.querySelector('table').
           insertAdjacentHTML('afterBegin', myTable)
        } else {
          console.log(`Error code ${req.status}`);
        }
    } catch (err) {console.log(err)}
  } 
 CsvToTable(document.querySelector('[data-csv]'))
</script>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)