SimpleXLSXGen

repository·master·Indexed 22 days ago

https://github.com/shuchkin/simplexlsxgen

A lightweight PHP library for exporting data to Excel XLSX files without external tools or heavy dependencies. It supports 2D array exports via fromArray(), multiple sheets, cell formatting using HTML-like tags, and advanced layout configurations such as merging cells, freezing panes, and setting column widths. The library includes utilities for date-to-excel conversion and coordinate mapping.

Tokens
4.7K
Snippets
20
Records
23
Agent score
28%

What's inside SimpleXLSXGen

  1. Handle RAW strings to disable type detection

    master

    By default, SimpleXLSXGen attempts to detect data types. To prevent this (e.g., to keep leading zeros in phone numbers or prevent dates from being parsed incorrectly), use one of the following methods:

    1. Prefix with null byte: Prepend "\0" to your string.
    2. Use SimpleXLSXGen::raw(): Wrap the value in this method.
    3. Use SimpleXLSXGen::rawArray(): Pass the entire 2D array through this method before calling fromArray().
    4. Use <raw> tag: Wrap the content in <raw>...</raw> tags.
    // Option 1: Null byte prefix
    $data = [["\0" . '+12345']];
    
    // Option 2: ::raw() method
    $data = [SimpleXLSXGen::raw('20- short term: <6 month')];
    
    // Option 3: ::rawArray() method
    $data = [['test', 'raw'], ['2025-01-01', '<tag>']];
    $raw_data = SimpleXLSXGen::rawArray($data);
    SimpleXLSXGen::fromArray($raw_data)->saveAs('test.xlsx');
    
    // Option 4: <raw> tag
    $data = [['<raw>+123456</raw>']];
  2. Format cells using HTML-like tags

    master

    SimpleXLSXGen supports basic HTML-like tags within cell strings to apply formatting.

    Text Styles:

    • Bold: <b>text</b>
    • Italic: <i>text</i>
    • Underline: <u>text</u>
    • Strike: <s>text</s>
    • Linebreaks: Use \n within the string.

    Cell Alignment:

    • <left>text</left>
    • <center>text</center>
    • <right>text</right>

    Advanced Styling via <style> tag:

    • Color: <style color="#FF0000">text</style>
    • Background Color: <style bgcolor="#FFFF00">text</style>
    • Font Size: <style font-size="32">text</style>
    • Borders: <style border="#000000">text</style> (supports none, thin, medium, dashed, dotted, thick, double, hair, etc.)
    • Border Sides: <style border="none dotted#0000FF medium#FF0000 double">...</style>
    • Row Height: <style height="50">text</style>
    • Cell Merging: Use <center>MERGE CELLS</center> (Note: The documentation shows this used in conjunction with mergeCells() method).
    $data = [
        ['Bold', '<b>12345.67</b>'],
        ['Green', '<style color="#00FF00">12345.67</style>'],
        ['Blue Text and Yellow Fill', '<style bgcolor="#FFFF00" color="#0000FF">12345.67</style>'],
        ['<top>Word wrap</top>', "<wraptext>Lorem Ipsum...</wraptext>"],
    ];
    SimpleXLSXGen::fromArray($data)->saveAs('styles.xlsx');
  3. Work with multiple sheets

    master

    You can generate an Excel file containing multiple sheets using either the fluid interface or the classic interface.

    Fluid Interface: Use addSheet($data, $sheetName) to append new sheets to the existing object.

    Classic Interface: Instantiate new SimpleXLSXGen() and call addSheet($data, $sheetName) multiple times.

    // Fluid interface
    Shuchkin\SimpleXLSXGen::fromArray( $books, 'My books' )
        ->addSheet( $books2, 'Second Sheet' )
        ->download();
    
    // Classic interface
    use Shuchkin\SimpleXLSXGen;
    $xlsx = new SimpleXLSXGen();
    $xlsx->addSheet( $books, 'Catalog 2021' );
    $xlsx->addSheet( $books2, 'Stephen King catalog');
    $xlsx->downloadAs('books_2021.xlsx');
  4. Basic Usage of SimpleXLSXGen

    master

    To export data to an Excel XLSX file, use the Shuchkin\SimpleXLSXGen::fromArray() method with a 2D array of data. You can then save the file, trigger a download, or cast the object to a string to get the raw XLSX content.

    Supported output methods:

    • saveAs('filename.xlsx'): Saves the file to the local filesystem.
    • downloadAs('filename.xlsx'): Triggers a browser download.
    • (string) $xlsx: Returns the raw XLSX content as a string.
    $books = [
        ['ISBN', 'title', 'author', 'publisher', 'ctry' ],
        [618260307, 'The Hobbit', 'J. R. R. Tolkien', 'Houghton Mifflin', 'USA'],
        [908606664, 'Slinky Malinki', 'Lynley Dodd', 'Mallinson Rendel', 'NZ']
    ];
    $xlsx = Shuchkin\SimpleXLSXGen::fromArray( $books );
    $xlsx->saveAs('books.xlsx');
  5. Install SimpleXLSXGen

    master

    The recommended way to install SimpleXLSXGen is via Composer. This will install the latest supported version.

    Alternatively, you can download the SimpleXLSXGen.php class file directly from the repository.

    $ composer require shuchkin/simplexlsxgen
  6. Configure sheet properties and layout

    master

    You can use a fluid interface to configure the overall Excel document properties and layout after creating the object.

    Layout & Appearance:

    • setDefaultFont('Font Name'): Sets the default font for the workbook.
    • setDefaultFontSize(size): Sets the default font size.
    • setColWidth(index|range, width): Sets column width. Accepts integer index (e.g., 1) or column letters/ranges (e.g., 'A' or 'B:C').
    • mergeCells('range'): Merges a range of cells (e.g., 'A20:B20').
    • autoFilter('range'): Applies an autofilter to a range.
    • freezePanes('cell'): Freezes rows and columns from the top-left up to, but not including, the specified cell.
    • rightToLeft(): Enables Right-to-Left mode.

    Metadata:

    • setAuthor(string)
    • setCompany(string)
    • setManager(string)
    • setLastModifiedBy(string)
    • setTitle(string)
    • setSubject(string)
    • setKeywords(string)
    • setDescription(string)
    • setCategory(string)
    • setLanguage(string)
    • setApplication(string)
    SimpleXLSXGen::fromArray($data)
        ->setDefaultFont('Courier New')
        ->setDefaultFontSize(14)
        ->setColWidth('B:C', 20)
        ->mergeCells('A20:B20')
        ->saveAs('styles_and_tags.xlsx');
  7. Create Hyperlinks

    master

    SimpleXLSXGen supports several types of hyperlinks:

    • Automatic detection: Standard URLs (e.g., https://example.com) and email addresses (e.g., mailto:info@example.com) are automatically detected.
    • HTML Anchor tags: Use <a href="URL">Anchor Text</a> for custom text.
    • Internal links: Link to other sheets using <a href="'Sheet Name'!A1">Text</a>.
    • Relative links: Link to other files using <a href="books.xlsx">Text</a>.
    $xlsx = SimpleXLSXGen::fromArray([
        ['internal link', '<a href="\'My books 2\'!A1">Go to second sheet</a>'],
        ['http', 'https://example.com/'],
        ['mailto', 'info@example.com'],
    ])->addSheet([['Second sheet']], 'My books 2')->saveAs('hyperlinks.xlsx');
  8. Save an XLSX file to disk

    master

    Use saveAs($filename) to write the generated Excel file to a specific path on your server. The filename is sanitized to remove null bytes, carriage returns, newlines, tabs, and double quotes.

    If you want to use the default filename (which defaults to the workbook title or a timestamp), use save().

    // Save to a specific filename
    $xlsx->saveAs('reports/monthly_report.xlsx');
    
    // Save using default name (Title or YmdHi.xlsx)
    $xlsx->save();
  9. Convert dates and times to Excel format

    master

    To ensure dates and times are recognized correctly by Excel, use the SimpleXLSXGen::date2excel() static method. This converts date/time components into the floating-point number format used by Excel.

    Signature: public static function date2excel($year, $month, $day, $hours = 0, $minutes = 0, $seconds = 0)

    $excelDate = SimpleXLSXGen::date2excel(2023, 10, 25, 14, 30, 0);
  10. Set column widths

    master

    Adjust the width of columns using setColWidth($col, $width). The $col parameter supports several formats:

    • An integer (1-based index).
    • A column letter (e.g., 'A', 'AA').
    • A range of columns (e.g., 'A:C').

    The $width parameter is an integer representing the width in characters.

    $xlsx->setColWidth('A', 10);
    $xlsx->setColWidth('B:D', 20);
    $xlsx->setColWidth(5, 15);
  11. Add multiple sheets to a workbook

    master

    To create a workbook with multiple sheets, instantiate the class and call addSheet() for each new sheet. Each call to addSheet() increments the sheet count and manages sheet naming automatically if a name is not provided.

    addSheet() accepts:

    • $rows: A 2D array of data for the sheet.
    • $name: (Optional) A string for the sheet name (max 31 characters).
    use Shuchkin\SimpleXLSXGen;
    
    $xlsx = new SimpleXLSXGen();
    
    // Add first sheet
    $xlsx->addSheet([
        ['Data 1', 'Data 2'],
        ['Val 1', 'Val 2'],
    ], 'First Sheet');
    
    // Add second sheet
    $xlsx->addSheet([
        ['Info A', 'Info B'],
        ['X', 'Y'],
    ], 'Second Sheet');
  12. Initialize SimpleXLSXGen

    master

    You can create a new instance of SimpleXLSXGen using the create() static method or by instantiating the class directly. The create() method allows you to optionally set a title for the Excel file immediately.

    By default, the generator uses 'Calibri' as the font with a size of 10.

    use Shuchkin\SimpleXLSXGen;
    
    // Option 1: Using create() with an optional title
    $xlsx = SimpleXLSXGen::create('My Excel Report');
    
    // Option 2: Standard instantiation
    $xlsx = new SimpleXLSXGen();