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

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>
  <link rel=stylesheet 
  <div class=container >
    <h1>CSV File to Table</h1>
    <h3>Events for February</h3>
    <table data-csv=events.csv></table>
  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.forEach((aktRow) => {
           insertAdjacentHTML('afterBegin', myTable)
        } else {
          console.log(`Error code ${req.status}`);
    } catch (err) {console.log(err)}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)