How to convert a HTML table data into CSV file in Javascript | HTML data in Excel | letsbug

     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


Comments

Categories

Big Data Analytics Binary Search Binary Search Tree Binary To Decimal binary tree Breadth First Search Bubble sort C Programming c++ Chemical Reaction and equation class 10 class 10th Class 9 Climate Complex Numbers computer network counting sort CSS Cyber Offenses Cyber Security Cyberstalking Data Science Data Structures Decimal To Binary Development diamond pattern Digital Marketing dust of snow Economics Economics Lesson 4 Email Validation English fire and ice Food Security in India Footprints Without feet Forest And Wildlife Resources game Geography Geography lesson 6 glassmorphism Glossary Graph HackerRank Solution hindi HTML image previewer India-Size And Location Insertion Sort Internet Network Status Interview Questions Introduction to cyber crime and cyber security IT javascript tricks json to CSV converter lesson 2 lesson 1 lesson 2 Lesson 3 Lesson 6 lesson 7 Life lines of National Economy life processes Linear Search Linked List lowest common ancestor Machine Learning MCQs median in array Merge sort min and max of two numbers Moment Money and Credit My Childhood Natural Vegetation and Wildlife NCERT Network connectivity devices Network Models Network Security No Men Are foreign Node.js operator overloading P5.js PHP Physical features of India Population Prime Numbers python Quick sort R language Rain on the roof Regular Expression Resources and development reversing array saakhi science Searching Algorithm Selection sort Social Media Marketing social science Software Engineering Software Testing Sorting Algorithm Stacks staircase pattern System Concepts Text Recognition The last Leaf time converter Time Passed From A Date Todo List App Tree Trending Technologies Understanding Economic Development username and password video player Visualization water resources Wired And Wireless LAN साखी
Show more

Popular Posts

Big Data MCQs(multiple choice questions) with answers - letsbug

Digital Marketing MCQ(Multiple Choice Questions) with Answers | part 1 | letsbug

Software Engineering MCQs questions with answers - letsbug