Skip to content

wyMinLwin/to-xlsx

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

42 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

to-xlsx

A powerful JavaScript/TypeScript library for exporting data to Excel XLSX files with advanced formatting, grouping, and calculation features.

npm version License: MIT

โœจ Features

  • ๐Ÿ“Š Export Arrays to Excel - Convert JavaScript/TypeScript arrays to XLSX files
  • ๐ŸŽจ Advanced Styling - Customize colors, fonts, backgrounds, and borders
  • ๐Ÿ“ Custom Headers & Titles - Add custom column headers and report titles
  • ๐Ÿ“ Column Management - Set custom widths, reorder, merge, or exclude columns
  • ๐Ÿ—‚๏ธ Data Grouping - Group data with custom conditions and styled subtitles
  • ๐Ÿ“„ Multi-Sheet Support - Split data across multiple worksheets
  • ๐Ÿงฎ Calculations - Automatic subtotals and grand totals with multiple operations
  • ๐ŸŽฏ TypeScript Support - Full type safety and IntelliSense support

๐Ÿ“ฆ Installation

# npm
npm install to-xlsx

# pnpm
pnpm add to-xlsx

# yarn
yarn add to-xlsx

๐Ÿš€ Quick Start

import { exportToXlsx } from "to-xlsx";

const data = [
    { name: "John", age: 28, department: "IT", salary: 45000 },
    { name: "Jane", age: 32, department: "HR", salary: 55000 },
    { name: "Bob", age: 25, department: "IT", salary: 35000 },
];

// Basic export
exportToXlsx({
    data,
    fileName: "employees",
});

๐Ÿ“š Usage Examples

๐ŸŽจ Styled Export with Custom Headers

exportToXlsx({
    data: employees,
    fileName: "employee-report",
    title: {
        text: "Employee Directory",
        bg: "4472C4",
        color: "FFFFFF",
        fontSize: 16,
        border: {
            all: { style: "thick", color: "000000" },
        },
    },
    columnHeaders: {
        name: "Full Name",
        age: "Age",
        department: "Department",
        salary: "Annual Salary",
    },
    columnSizes: {
        name: 25,
        age: 10,
        department: 20,
        salary: 15,
    },
    columnsStyle: {
        bg: "70AD47",
        color: "FFFFFF",
        fontSize: 12,
    },
});

๐Ÿ—‚๏ธ Data Grouping with Subtotals

exportToXlsx({
    data: employees,
    fileName: "employees-by-age-group",
    groupBy: {
        conditions: [
            {
                label: "Young (Under 30)",
                filter: (item) => item.age < 30,
            },
            {
                label: "Mid-Career (30-40)",
                filter: (item) => item.age >= 30 && item.age < 40,
            },
            {
                label: "Senior (40+)",
                filter: (item) => item.age >= 40,
            },
        ],
        subtitleStyle: {
            bg: "BDD7EE",
            color: "000000",
            fontSize: 14,
            border: {
                bottom: { style: "medium", color: "0070C0" },
            },
        },
        showSubtotals: true,
        subtotalStyle: {
            bg: "E6F3FF",
            color: "000000",
            fontSize: 11,
            border: {
                all: { style: "thin", color: "0070C0" },
            },
        },
    },
    totals: {
        columns: ["salary"],
        showGrandTotal: true,
        subtotalLabel: "Group Subtotal",
        grandTotalLabel: "Total Company Payroll",
        operations: {
            salary: "sum",
        },
        grandTotalStyle: {
            bg: "4472C4",
            color: "FFFFFF",
            fontSize: 13,
            border: {
                all: { style: "thick", color: "000000" },
            },
        },
    },
});

๐Ÿงฎ Advanced Calculations

exportToXlsx({
    data: salesData,
    fileName: "sales-analysis",
    totals: {
        columns: ["quantity", "revenue", "profit"],
        showGrandTotal: true,
        operations: {
            quantity: "sum", // Total units sold
            revenue: "sum", // Total revenue
            profit: "avg", // Average profit margin
        },
        grandTotalLabel: "SUMMARY TOTALS",
    },
});

๐Ÿ”— Column Merging

exportToXlsx({
    data: employees,
    columnsMerge: [
        {
            keys: {
                startColumn: "firstName",
                endColumn: "lastName",
            },
            columnName: "Personal Info",
        },
        {
            keys: {
                startColumn: "department",
                endColumn: "salary",
            },
            columnName: "Work Details",
        },
    ],
});

๐Ÿ“„ Multi-Sheet Export

exportToXlsx({
    data: employees,
    sheetsBy: {
        key: "department",
        namePattern: "$key Department", // Creates sheets like "IT Department", "HR Department"
    },
});

๐Ÿ“– API Reference

exportToXlsx(props: Props<T>)

Main function to export data to Excel.

Props

Property Type Description Default
data T[] Array of data objects to export Required
fileName string Output file name (without extension) "ExportSheet"
columnHeaders Record<string, string> Custom column headers null
columnSizes Record<string, number> Column widths null
columnsStyle ColumnsStyleType Header row styling null
columnsOrder string[] Custom column order null
columnsMerge ColumnsMergeType Merge column headers null
excludeColumns string[] Columns to exclude null
sheetsBy SheetsByType Split into multiple sheets null
title TitleType Report title configuration null
groupBy GroupByType<T> Data grouping configuration null
totals TotalsType Calculations configuration null

Type Definitions

TitleType

{
    text: string;
    bg?: string;           // Background color (hex)
    color?: string;        // Text color (hex)
    fontSize?: number;     // Font size
    border?: BorderType;   // Border styling
}

GroupByType<T>

{
    conditions: GroupCondition<T>[];
    subtitleStyle?: {
        bg?: string;
        color?: string;
        fontSize?: number;
        border?: BorderType;
    };
    showSubtotals?: boolean;      // Enable subtotal rows
    subtotalStyle?: {             // Subtotal row styling
        bg?: string;
        color?: string;
        fontSize?: number;
        border?: BorderType;
    };
}

TotalsType

{
    columns: string[];                    // Columns to calculate
    showGrandTotal?: boolean;            // Show grand total row
    subtotalLabel?: string;              // Subtotal row label
    grandTotalLabel?: string;            // Grand total row label
    operations?: {                       // Calculation operations
        [columnName: string]: 'sum' | 'avg' | 'count' | 'min' | 'max';
    };
    grandTotalStyle?: {                  // Grand total styling
        bg?: string;
        color?: string;
        fontSize?: number;
        border?: BorderType;
    };
}

BorderType

{
    top?: BorderStyleType;
    left?: BorderStyleType;
    bottom?: BorderStyleType;
    right?: BorderStyleType;
    all?: BorderStyleType;    // Shorthand for all borders
}

BorderStyleType

{
    style?: 'thin' | 'dotted' | 'dashDot' | 'hair' | 'dashDotDot' |
            'slantDashDot' | 'mediumDashed' | 'mediumDashDotDot' |
            'mediumDashDot' | 'medium' | 'double' | 'thick';
    color?: string;           // Border color (hex)
}

๐ŸŽจ Styling Guide

Colors

Use hex color codes without the # symbol:

  • "FF0000" for red
  • "00FF00" for green
  • "0000FF" for blue
  • "FFFFFF" for white
  • "000000" for black

Border Styles

Available border styles in order of thickness:

  • hair โ†’ thin โ†’ medium โ†’ thick
  • dotted, dashDot, dashDotDot for patterns
  • double for double lines

๐Ÿงฎ Calculation Operations

Operation Description Example Use Case
sum Addition of all values Total sales, quantities
avg Average of all values Average price, rating
count Count of non-empty values Number of items
min Minimum value Lowest price
max Maximum value Highest score

๐Ÿ”ง Advanced Features

Data Filtering for Groups

Use custom filter functions for flexible grouping:

groupBy: {
    conditions: [
        {
            label: "High Performers",
            filter: (employee) => employee.rating >= 4.5 && employee.salary > 60000,
        },
        {
            label: "New Hires",
            filter: (employee) => new Date(employee.hireDate) > new Date("2024-01-01"),
        },
    ];
}

Multiple Calculation Types

Different operations on different columns:

totals: {
    columns: ["quantity", "price", "rating"],
    operations: {
        quantity: "sum",    // Total units
        price: "avg",       // Average price
        rating: "max"       // Best rating
    }
}

๐Ÿ› ๏ธ Dependencies

๐Ÿค Contributing

Contributions are welcome! Please see our Contributing Guide for details.

๐Ÿ“‹ Code of Conduct

This project follows our Code of Conduct. Please read it before contributing.

๐Ÿ“„ License

Licensed under the MIT License.

About

Export to excel with a function

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Packages

No packages published