Skip to content
Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones

Categories

  • Automobiles (12)
    • Cars (7)
  • Blog (103)
    • Poems (2)
    • Space (2)
  • Command (2)
  • Education (2)
  • Entertainment (4)
  • Gadgets (9)
    • Phones (8)
      • Android Phones (4)
  • HTML Templates (11)
  • IT Training Institutes (1)
  • Lifestyle (4)
  • News (51)
  • Others (23)
  • Programming (296)
    • API (16)
    • CSS (83)
    • Database (4)
    • Hosting (1)
    • HTML (37)
    • JavaScript (117)
      • JQuery (27)
      • ReactJS (7)
    • PHP (116)
  • Python (3)
  • recipes (1)
  • SEE Result (1)
  • Server (3)
  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones
Close

Search

ProgrammingJQuery

CSV Read and Write Using jQuery

By Admin
December 19, 2024 4 Min Read
0

In this tutorial, we’ll walk through how to read, display, and modify CSV files using jQuery. We’ll create an interactive web page that allows users to upload a CSV file, view its contents in a table, make edits, and download the modified CSV. The tutorial uses jQuery to simplify DOM manipulation and file handling.

Follow this video for complete guidance:

Setting Up the HTML Structure

We’ll begin by setting up a simple HTML page with the necessary inputs and table to handle the CSV file.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>CSV Editor</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    </head>
    <body class="bg-light py-5">
        <div class="container">
            <h1 class="text-center mb-4">CSV Editor</h1>
            <div class="mb-3">
                <input type="file" id="csvFile" accept=".csv" class="form-control" />
            </div>
            <button id="downloadBtn" class="btn btn-primary mb-3">Download CSV</button>
            <table id="csvTable" class="table table-bordered table-striped"></table>
        </div>
    </body>
</html>
  • File Input: The allows users to upload a CSV file.
  • Download Button: A button to download the edited CSV file.
  • Table: A element where the CSV data will be displayed and edited.

Reading the CSV File

When a file is selected, we will use the FileReader API to read the CSV file and display its contents in the table.

$('#csvFile').on('change', function () {
    const file = this.files[0];  // Get the selected file
    if (file) {
        const reader = new FileReader();  // Create a new FileReader
        reader.onload = e => renderTable(e.target.result);  // On file read, call renderTable
        reader.readAsText(file);  // Read the file as text
    }
});
  • FileReader: The FileReader is used to read the contents of the uploaded file as a text string.
  • renderTable function: After the file is read, we pass its contents to the renderTable function.

Rendering CSV Data as a Table

The renderTable function will process the CSV text, split it into rows and columns, and dynamically populate the table.

function renderTable(data) {
    const rows = data.trim().split('\n');  // Split CSV into rows
    const table = $('#csvTable').empty();  // Clear the table
    rows.forEach(row => {
        const cols = row.split(',');  // Split row into columns
        const tr = $('<tr>');  // Create a new table row
        cols.forEach(col => {
            $('<td>', {
                text: col,  // Set cell text
                contentEditable: true  // Make the cell editable
            }).appendTo(tr);  // Append to row
        });
        table.append(tr);  // Append row to table
    });
}
  • Splitting Rows and Columns: The split() method is used to separate the CSV text into rows and then further into columns.
  • Editable Cells: Each cell is made editable by setting contentEditable: true.
  • Appending Data: Each row () is appended to the table, and each column () is appended to the row.

Downloading the Edited CSV

After the table is displayed and possibly edited by the user, the “Download CSV” button allows them to download the modified table content as a CSV file.

$('#downloadBtn').on('click', () => {
    const csvContent = $('#csvTable tr').get().map(row => 
        $(row).find('td').get().map(td => $(td).text().trim()).join(',')
    ).join('\n');  // Convert table data into CSV format

    const blob = new Blob([csvContent], { type: 'text/csv' });  // Create a Blob for CSV
    const url = URL.createObjectURL(blob);  // Create a URL for the Blob

    $('<a>', { href: url, download: 'edited.csv' })[0].click();  // Trigger download
    URL.revokeObjectURL(url);  // Revoke the object URL
});
  • Extracting Table Data: We use jQuery to loop through each row and cell, get the text, trim it, and join the values with commas to form CSV content.
  • Creating a Blob: The CSV data is wrapped in a Blob, which is a binary representation of the file.
  • Download Link: An anchor
  • tag is created dynamically, and a click event is triggered programmatically to initiate the file download.
  • Revoke URL: The created object URL is revoked after the download is triggered to free up memory.

Complete Working Code

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>CSV Editor</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    </head>
    <body class="bg-light py-5">
        <div class="container">
            <h1 class="text-center mb-4">CSV Editor</h1>
            <div class="mb-3">
                <input type="file" id="csvFile" accept=".csv" class="form-control" />
            </div>
            <button id="downloadBtn" class="btn btn-primary mb-3">Download CSV</button>
            <table id="csvTable" class="table table-bordered table-striped"></table>
        </div>

        <script>
        // Read CSV File
        $('#csvFile').on('change', function () {
            const file = this.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = e => renderTable(e.target.result);
                reader.readAsText(file);
            }
        });

        // Render CSV as Table
        function renderTable(data) {
            const rows = data.trim().split('\n');
            const table = $('#csvTable').empty();
            rows.forEach(row => {
                const cols = row.split(',');
                const tr = $('<tr>');
                cols.forEach(col => $('<td>', {
                    text: col,
                    contentEditable: true
                }).appendTo(tr));
                table.append(tr);
            });
        }

        // Download Edited CSV
        $('#downloadBtn').on('click', () => {
            const csvContent = $('#csvTable tr').get().map(row => 
                $(row).find('td').get().map(td => $(td).text().trim()).join(',')
            ).join('\n');

            const blob = new Blob([csvContent], { type: 'text/csv' });
            const url = URL.createObjectURL(blob);

            $('<a>', { href: url, download: 'edited.csv' })[0].click();
            URL.revokeObjectURL(url);
        });
        </script>
    </body>
</html>

This simple CSV editor allows you to load CSV files, view and edit them in a table format, and download the modified CSV file. Using jQuery for DOM manipulation and file handling simplifies the process, making it easy to interact with the CSV data on the client side without a backend.

Tags:

csvJQuery
Author

Admin

Follow Me
Other Articles
Previous

Develop a Custom Search Engine Using PHP and MySQL

Next

Building a Twitter Clone with HTML, CSS, and Bootstrap

No Comment! Be the first one.

Leave a Reply

Your email address will not be published. Required fields are marked *

FIFA World Cup 2026 Predict and Win by SportsGuff

Recent Posts

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide
  • Chiranjibi Adhikari Appointed Acting President of CAN Federation
  • How to Design a Student Marksheet Using HTML and CSS

Tags

adsense ai animate animation animation using HTML and CSS API blog calculator chatgpt Cryptocurrency CSS css animation design Email Facebook featured filemanager file manager free template google htaccess HTML image Instagram interview javascript JQuery jquery ui NADA AutoShow NADA Auto Show 2024 password PHP Progressive Web App PWA QR random react reactjs Rotate travel Twitter vpn youthforum youthsforum youtube

About Us

At Youths Forum, we are passionate about sharing knowledge that empowers students, educators, professionals, and technology enthusiasts.

Our Mission

Our mission is simple: to make technology and education accessible, understandable, and beneficial for everyone. We strive to create content that helps our readers learn new skills and stay updated with industry developments.

RSS RSS

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You Admin
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide Admin
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide Admin

Quick Links

  • Stock Market Live
  • Parliament Election 2082
Copyright 2026 — Youths Forum. All rights reserved. Blogsy WordPress Theme