Tag: xlsx Library

  • How to Read and Write Excel Files in Node.js with the SheetJS (xlsx) Library

    To read and write Excel files in Node.js, the most popular library is xlsx (from the SheetJS project). It supports .xlsx, .xls, and .csv formats and is easy to use.


    ✅ Step-by-Step Guide to Read & Write Excel Files in Node.js

    📦 Step 1: Install the xlsx Package

    Run the following command:

    npm install xlsx
    

    📘 Example: Writing to an Excel File

    const XLSX = require('xlsx');
    
    // Sample data
    const data = [
      ["Name", "Age", "City"],
      ["John", 30, "New York"],
      ["Alice", 25, "London"],
      ["Bob", 35, "Paris"]
    ];
    
    // Create a new workbook and worksheet
    const worksheet = XLSX.utils.aoa_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
    
    // Write to file
    XLSX.writeFile(workbook, "output.xlsx");
    
    console.log("Excel file written successfully!");
    

    📘 Example: Reading from an Excel File

    const XLSX = require('xlsx');
    
    // Read the Excel file
    const workbook = XLSX.readFile('output.xlsx');
    
    // Get the first sheet
    const sheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[sheetName];
    
    // Convert to JSON
    const jsonData = XLSX.utils.sheet_to_json(worksheet);
    
    console.log("Excel file data:");
    console.log(jsonData);
    

    🔁 Input/Output Summary

    ActionMethod
    Read fileXLSX.readFile(filename)
    Write fileXLSX.writeFile(workbook, filename)
    Create sheetXLSX.utils.aoa_to_sheet(data)
    Convert to JSONXLSX.utils.sheet_to_json(sheet)

    📝 Notes

    • AOA (Array of Arrays): Best for simple table-like data.
    • sheet_to_json() gives you an array of objects for easy processing.

    Absolutely! Here’s an explanation of where and why you might need to read and write Excel files in Node.js, followed by real-world use cases.


    📌 Where Is Excel File Handling Required in Node.js?

    Working with Excel files in a Node.js backend or application is useful when your system needs to:

    ✅ 1. Export Reports or Data to Excel

    When users want to download reports, sales data, invoices, or analytics in Excel format.

    Example:

    • A web dashboard that allows exporting user activity logs as .xlsx
    • An admin panel that exports inventory or orders

    ✅ 2. Read Uploaded Excel Files

    When users upload Excel files containing data to be processed, imported, or validated.

    Example:

    • HR uploads employee records in Excel
    • Accountants upload tax or ledger entries in .xlsx
    • Students upload answer sheets or marksheets

    ✅ 3. Data Migration

    Reading old Excel files and importing them into a new system or database.

    Example:

    • Migrating legacy data from Excel to MongoDB or MySQL
    • Uploading master data like product catalogs or customer lists

    ✅ 4. Automation and Scheduled Tasks

    Scheduled scripts that read Excel templates, process them, and generate output.

    Example:

    • Nightly script that reads a .xlsx report and emails a summary
    • Cron job that reads monthly sales targets from Excel and stores them in the database

    ✅ 5. Online Formatted Excel Generation

    When users fill out a form and get a custom Excel report/download with formatting.

    Example:

    • Loan EMI calculators generating .xlsx reports
    • Quotation generators for e-commerce or B2B services

    💼 Real-World Use Cases

    Use CaseDescription
    School Management SystemImport student data, export mark sheets
    E-commerce Admin PanelExport order lists or product catalogs
    Finance / Payroll AppGenerate payslips, read salary structures
    Inventory ManagementUpload or download stock records
    CRM SystemsExport contacts or leads

    🔧 Why Use Node.js for Excel?

    • Fast, scalable backend
    • Easily integrates with frontends (React, Angular, etc.)
    • Works well with REST APIs and file uploads
    • Supports real-time and batch processing

    On sale products

  • How to Convert JSON to Excel File Using JavaScript (Step-by-Step Guide)


    ✅ What is JSON and Why Convert It to Excel?

    • JSON (JavaScript Object Notation) is a lightweight format to store and exchange data, commonly used in web APIs.
    • Excel (.xlsx) is a widely used spreadsheet format that allows users to view, analyze, and share data easily.

    Converting JSON to Excel allows users to:

    • View JSON data in a readable tabular format.
    • Perform data analysis or reporting in Excel.
    • Download data from a web app for offline use.

    🛠 Tool Required: SheetJS (xlsx Library)

    SheetJS is the most popular JavaScript library for working with Excel files. It works in both browser and Node.js environments.


    💻 1. Using SheetJS in Browser (Client-Side)

    Step 1: Include the Library

    Add this <script> tag in your HTML file:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    

    Step 2: Define Your JSON Data

    This is the data you want to convert to Excel:

    const jsonData = [
      { Name: "John", Age: 30, City: "New York" },
      { Name: "Anna", Age: 22, City: "London" },
      { Name: "Mike", Age: 32, City: "Chicago" }
    ];
    

    Step 3: Create Button & Download Function

    <button onclick="downloadExcel()">Download Excel</button>
    
    <script>
    function downloadExcel() {
      // Step 1: Convert JSON to Sheet
      const worksheet = XLSX.utils.json_to_sheet(jsonData);
      
      // Step 2: Create a new Workbook
      const workbook = XLSX.utils.book_new();
      
      // Step 3: Append Sheet to Workbook
      XLSX.utils.book_append_sheet(workbook, worksheet, "MyData");
      
      // Step 4: Export Workbook to Excel File
      XLSX.writeFile(workbook, "myData.xlsx");
    }
    </script>
    

    👉 When the button is clicked, an Excel file named myData.xlsx will be downloaded.


    📦 2. Using SheetJS in Node.js (Server-Side)

    Step 1: Install the Library

    npm install xlsx
    

    Step 2: Write the JavaScript Code

    const XLSX = require("xlsx");
    
    // Sample JSON data
    const jsonData = [
      { Name: "John", Age: 30, City: "New York" },
      { Name: "Anna", Age: 22, City: "London" },
      { Name: "Mike", Age: 32, City: "Chicago" }
    ];
    
    // Step 1: Convert JSON to Sheet
    const worksheet = XLSX.utils.json_to_sheet(jsonData);
    
    // Step 2: Create a new Workbook
    const workbook = XLSX.utils.book_new();
    
    // Step 3: Append the Sheet
    XLSX.utils.book_append_sheet(workbook, worksheet, "MyData");
    
    // Step 4: Write Excel File to Disk
    XLSX.writeFile(workbook, "output.xlsx");
    
    console.log("Excel file created successfully!");
    

    👉 Run this file using node filename.js. You’ll get output.xlsx in the project folder.


    🎨 Optional: Customize Your Output

    1. Set Custom Column Order

    XLSX.utils.json_to_sheet(jsonData, {
      header: ["Name", "City", "Age"]  // custom column order
    });
    

    2. Add Column Titles (Headers)

    // Already done by default from JSON keys
    

    3. Format Dates or Numbers

    • You can format data before passing it to SheetJS.
    • For advanced styling (colors, fonts, borders), use xlsx-style fork or export CSV.

    📁 Extra Tip: Convert to CSV Instead of Excel

    If you want a .csv file instead:

    const csv = XLSX.utils.sheet_to_csv(worksheet);
    fs.writeFileSync("output.csv", csv);
    

    ✅ Summary

    TaskSheetJS Function
    Convert JSON to SheetXLSX.utils.json_to_sheet()
    Create WorkbookXLSX.utils.book_new()
    Add Sheet to BookXLSX.utils.book_append_sheet()
    Export Excel FileXLSX.writeFile()

    📦 Final Output

    You get an .xlsx file with your JSON data organized in rows and columns, ready to open in Microsoft Excel, Google Sheets, or LibreOffice.


    On sale products