CSV Read and Write Using jQuery

0
59

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.
ALSO READ  Dynamic Student ID Card with HTML, CSS, and jQuery

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.
ALSO READ  Easy Football Lineup Selection with jQuery UI Drag Drop

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.

Comments are closed.