How to Upload File in JS | File Upload Program in JavaScript | JS

To create a JavaScript program that allows you to upload an Excel file and fetch the data to display it on a web page, you can use libraries like SheetJS (xlsx.js) to read Excel files in JavaScript. Here's a basic approach.

Steps

  1. Install SheetJS (xlsx.js)
  2. Create an HTML form for file upload
  3. Parse the uploaded Excel file
  4. Display the data on the webpage

Code Example

HTML file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel Data Upload</title>
</head>
<body>
    <h1>Upload Excel File</h1>
    <input type="file" id="upload" />
    <table id="excelDataTable" border="1">
        <!-- Data will be dynamically injected here -->
    </table>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script>
        // Listen for file input changes
        document.getElementById('upload').addEventListener('change', handleFile, false);

        function handleFile(e) {
            const file = e.target.files[0];
            const reader = new FileReader();

            reader.onload = function(event) {
                const data = new Uint8Array(event.target.result);
                const workbook = XLSX.read(data, { type: 'array' });

                // Get first worksheet
                const sheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[sheetName];

                // Convert sheet to JSON
                const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

                // Display the data in a table
                displayData(jsonData);
            };

            reader.readAsArrayBuffer(file);
        }

        function displayData(data) {
            const table = document.getElementById('excelDataTable');
            table.innerHTML = ''; // Clear any existing data

            // Loop through rows and cells
            data.forEach((row) => {
                let rowElement = document.createElement('tr');

                row.forEach((cell) => {
                    let cellElement = document.createElement('td');
                    cellElement.textContent = cell;
                    rowElement.appendChild(cellElement);
                });

                table.appendChild(rowElement);
            });
        }
    </script>
</body>
</html>

Markup

Copy

Explanation

  1. File Upload: This HTML allows users to select an Excel file using an <input type="file">.
  2. File Reading: Using FileReader API, the uploaded file is read as an ArrayBuffer.
  3. SheetJS: The SheetJS library parses the Excel file and converts it to JSON format.
  4. Table Display: The data is then injected into an HTML table dynamically.

How does it work?

  • When the user uploads an Excel file, the JavaScript program processes it, reads the first sheet, and displays the data in a table format.
  • You can extend this program to handle more sheets, and specific columns, or format the data better according to your requirements.

To load an Excel file and display its contents on a web page without installing external libraries like SheetJS (xlsx.js), you would need to manually parse the file. However, JavaScript does not natively support reading Excel files, and manual parsing would require quite complex logic. Therefore, using pure JavaScript (without external libraries) to read a .xlsx file is quite difficult.

That said, here are a couple of alternative approaches you could consider.

1. Use CSV Instead of Excel

You can convert your Excel file to a CSV file and use JavaScript’s built-in capabilities to read and parse the CSV file.

Example for CSV

Here’s how you could handle a CSV file upload and display its content on a web page without external libraries.

HTML + JavaScript (For CSV Files)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSV File Upload</title>
</head>
<body>
    <h1>Upload CSV File</h1>
    <input type="file" id="upload" />
    <table id="csvDataTable" border="1">
        <!-- Data will be dynamically injected here -->
    </table>

    <script>
        document.getElementById('upload').addEventListener('change', function(e) {
            const file = e.target.files[0];

            if (!file.name.endsWith('.csv')) {
                alert('Please upload a CSV file!');
                return;
            }

            const reader = new FileReader();

            reader.onload = function(event) {
                const csvData = event.target.result;
                parseCSV(csvData);
            };

            reader.readAsText(file);
        });

        function parseCSV(csvData) {
            const rows = csvData.split('\n');
            const table = document.getElementById('csvDataTable');
            table.innerHTML = ''; // Clear existing table content

            rows.forEach(row => {
                const cells = row.split(',');
                const rowElement = document.createElement('tr');

                cells.forEach(cell => {
                    const cellElement = document.createElement('td');
                    cellElement.textContent = cell;
                    rowElement.appendChild(cellElement);
                });

                table.appendChild(rowElement);
            });
        }
    </script>
</body>
</html>

Markup

Copy

Explanation

  • This example handles CSV file uploads, reads the content using FileReader, and splits the CSV data by rows and columns.
  • It dynamically generates an HTML table to display the CSV content.

2. Convert Excel to CSV and Use the Above Code

You can convert your Excel file to CSV (using Excel or another program) and use the above approach. If your data is simple and doesn’t require specific Excel formatting or formulas, CSV should suffice.

Why CSV Is Better for This Task?

  • No External Libraries: You don’t need libraries to handle CSV, as it’s just text separated by commas.
  • Simple Parsing: JavaScript can easily parse CSV data with string manipulation functions like split().
Ebook Download
View all
Learn
View all