5

CSV-File to HTML <table>

 2 years ago
source link: https://dev.to/frankwisniewski/csv-file-to-html-209c
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Cover image for CSV-File to HTML <table>

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.

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK