Skip to content
Blog

Export an HTML Table to CSV in JavaScript

By Published A short read

     Hello, in this article we are doing a little project. We are doing this using HTML, CSS and Javascript so this is a web project. In this project we are going to see many things some of them are 

  1. Creating a dynamic data table in HTML using javascript
  2. Creating a beautiful looking table in HTML using css
  3. Converting a HTML table into a CSV file
  4. And adding a click animation on a button
Table design in HTML button click animation in css
Output main table and button

    So let's get started. 

How to Create Dynamic HTML Table

    To create a dynamic HTML table is very simple. Use javascript to this. You can grab the reference to the table using query selectors and then you can loop through the data which you wanted to add in the table and add them by create new tr and td in the table. 
   like this code below:

//sample data
const sample_Data = [{
        "Sr. No": "1",
        "Name": "Aniket",
        "Roll No": "1"
    },
    {
        "Sr. No": "2",
        "Name": "Aman",
        "Roll No": "2"
    },
    {
        "Sr. No": "3",
        "Name": "Ajay",
        "Roll No": "3"
    },

]
// add data to table
let table_body = document.querySelector('tbody')
sample_Data.forEach((data, index) => {
    let tr = document.createElement('tr')
    Object.keys(data).forEach((key) => {
        let td = document.createElement('td')
        td.innerText = data[key]
        tr.appendChild(td)
    })
    table_body.appendChild(tr)
})

Above is how you can add data dynamically to the table now lets see how the table looks like.
<table>
    <thead>
        <tr>
            <th>Sr. No</th>
            <th>Name </th>
            <th>Roll No</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

    Now lets add a button below the table and add some styling to it.

<!-- style should be in the head tag -->
<style>
    table {
        border-collapse: collapse;
        width: 100%;
    }

    td {
        border: 1px solid black;
        padding: 5px;
        text-align: center;
    }

    th {
        border: 1px solid black;
        padding: 5px;
        background-color: #ddd;
    }
    button{
        background-color: #4CAF50;
        color: white;
        padding: 14px 20px;
        margin: 8px 0;
        border: none;
        cursor: pointer;
        width: 100%;
    }
    button:hover{
        opacity: 0.8;
    }
    .click{
        animation: click .5s;
    }
    @keyframes click{
        0%{
            transform: scale(0.95);
        }
        100%{
            transform: scale(1);
        }
    }
</style>

<table>
    <thead>
        <tr>
            <th>Sr. No</th>
            <th>Name </th>
            <th>Roll No</th>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>
<!-- button should be in the body below the table -->
<button>Download CSV</button>

Above is how the button should go in the body and styles tag should be in the head tag just making it clear so you don't get confused.
Now that we have our table and button ready with the styles applied to them now move on to next thing.

Convert HTML Table Data To CSV

// download csv button
const download_csv_button = document.querySelector('button')
download_csv_button.addEventListener("click", ()=>{

    //click animation on the button
    download_csv_button.classList.add('click')
    setTimeout(() => {
        download_csv_button.classList.remove('click')
    }, 500)

    //creating a csv file
    let csv_data = sample_Data.map(data => Object.values(data).join(','))
    csv_data.unshift(Object.keys(sample_Data[0]).join(','))
    let csv_string = csv_data.join('\n')

    //creating a blob object
    const blob = new Blob([csv_string], {type: 'text/csv'})

    //creating a link
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'sample.csv'
    document.body.appendChild(a)
    a.click()
   
    //removing the link
    setTimeout(()=>{
        document.body.removeChild(a)
        URL.revokeObjectURL(url)
    },0)
})

    In the above code we set an CLICK event listener on the button and then fire a call back arrow function. In the function we first add .click class to the button and then remove it to create that click animation on the button.

    Then we loop over the sample_Data to convert it to CSV like data. Then after that we create a blob object from the CSV data which we had converted.  To blob constructor we pass in the CSV data and then specify the type of the file which in our case is "text/csv".

    After that we have a file we create a URL of that CSV file and then we create a anchor tag element to the body. Attaching it the href attribute to the URL of the file and then specify the download attribute with the file name with the extension. 

    Then just append the element and trigger the click to start downloading the file. After the file is downloaded we remove the link from the memory. And that's it. When you open the downloaded file it will open in excel.

Our project is completed. ☺

outputs:



Aniket singh HTML to CSV converter
File In excel
Json to CSV Converter Lesbug
When the CSV is downloading