Convert Figma logo to code with AI

shuchkin logosimplexlsx

Parse and retrieve data from Excel XLSx files

1,703
493
1,703
9

Top Related Projects

A pure PHP library for reading and writing spreadsheet files

4,220

Read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way

Lightweight XLSX Excel Spreadsheet Writer in PHP

🚀 PHP Extension for creating and reader XLSX files.

11,464

ARCHIVED

Quick Overview

SimpleXLSX is a lightweight PHP library for reading and writing Microsoft Excel XLSX files. It provides a simple and efficient way to work with Excel spreadsheets without requiring external dependencies or extensions.

Pros

  • Easy to use with a straightforward API
  • No external dependencies or PHP extensions required
  • Supports both reading and writing XLSX files
  • Lightweight and fast performance

Cons

  • Limited support for advanced Excel features
  • May not handle very large spreadsheets as efficiently as more robust libraries
  • Documentation could be more comprehensive

Code Examples

Reading an XLSX file:

require_once('SimpleXLSX.php');

if ($xlsx = SimpleXLSX::parse('file.xlsx')) {
    foreach ($xlsx->rows() as $row) {
        print_r($row);
    }
} else {
    echo SimpleXLSX::parseError();
}

Writing an XLSX file:

$data = [
    ['Year', 'Sales', 'Profit'],
    [2020, 5000, 1500],
    [2021, 6000, 2000],
    [2022, 7000, 2500]
];

$xlsx = SimpleXLSX::create();
$xlsx->addSheet($data);
$xlsx->saveAs('report.xlsx');

Reading specific cells:

if ($xlsx = SimpleXLSX::parse('file.xlsx')) {
    echo $xlsx->getCell(0, 'B2'); // get cell B2 from first sheet
    echo $xlsx->getCell(1, 'C3'); // get cell C3 from second sheet
}

Getting Started

  1. Install via Composer:

    composer require shuchkin/simplexlsx
    
  2. Or download the SimpleXLSX.php file and include it in your project:

    require_once('SimpleXLSX.php');
    
  3. Use the library in your PHP code:

    $xlsx = SimpleXLSX::parse('file.xlsx');
    if ($xlsx) {
        // Work with the XLSX data
    } else {
        echo SimpleXLSX::parseError();
    }
    

Competitor Comparisons

A pure PHP library for reading and writing spreadsheet files

Pros of PhpSpreadsheet

  • More comprehensive feature set, including advanced formatting and formula support
  • Better documentation and community support
  • Actively maintained with regular updates

Cons of PhpSpreadsheet

  • Larger footprint and higher memory usage
  • Steeper learning curve due to more complex API
  • Slower performance for simple read/write operations

Code Comparison

SimpleXLSX:

$xlsx = SimpleXLSX::parse('file.xlsx');
foreach ($xlsx->rows() as $row) {
    print_r($row);
}

PhpSpreadsheet:

$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("file.xlsx");
$worksheet = $spreadsheet->getActiveSheet();
foreach ($worksheet->getRowIterator() as $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(false);
    foreach ($cellIterator as $cell) {
        echo $cell->getValue() . "\t";
    }
    echo PHP_EOL;
}

SimpleXLSX is more straightforward for basic operations, while PhpSpreadsheet offers more control and flexibility at the cost of verbosity.

4,220

Read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way

Pros of Spout

  • More feature-rich, supporting both reading and writing of XLSX files
  • Better performance for large files due to streaming capabilities
  • Active development with regular updates and community support

Cons of Spout

  • More complex to set up and use, requiring more dependencies
  • Larger library size, which may impact project footprint
  • Steeper learning curve for beginners

Code Comparison

SimpleXLSX:

$xlsx = SimpleXLSX::parse('file.xlsx');
foreach ($xlsx->rows() as $row) {
    print_r($row);
}

Spout:

$reader = ReaderEntityFactory::createXLSXReader();
$reader->open('file.xlsx');
foreach ($reader->getSheetIterator() as $sheet) {
    foreach ($sheet->getRowIterator() as $row) {
        print_r($row->toArray());
    }
}
$reader->close();

Both libraries offer straightforward ways to read XLSX files, but Spout's approach is more verbose and provides more control over the reading process. SimpleXLSX is more concise and easier to use for simple tasks, while Spout offers more flexibility and features for complex operations.

Lightweight XLSX Excel Spreadsheet Writer in PHP

Pros of PHP_XLSXWriter

  • Faster performance for large datasets due to streaming output
  • Smaller memory footprint when working with large files
  • More advanced formatting options for cells and worksheets

Cons of PHP_XLSXWriter

  • Less intuitive API for simple tasks
  • Fewer options for reading existing XLSX files
  • Requires more setup and configuration for basic use cases

Code Comparison

PHP_XLSXWriter:

$writer = new XLSXWriter();
$writer->writeSheetHeader('Sheet1', array('Col1' => 'string', 'Col2' => 'string'));
$writer->writeSheetRow('Sheet1', array('A1', 'B1'));
$writer->writeToFile('example.xlsx');

SimpleXLSX:

$xlsx = SimpleXLSX::parse('example.xlsx');
foreach ($xlsx->rows() as $row) {
    print_r($row);
}

PHP_XLSXWriter is better suited for creating large XLSX files with complex formatting, while SimpleXLSX excels at reading and parsing existing XLSX files with a simpler API. The choice between the two depends on the specific requirements of your project, such as file size, performance needs, and whether you're primarily reading or writing XLSX files.

🚀 PHP Extension for creating and reader XLSX files.

Pros of php-ext-xlswriter

  • Significantly faster performance due to being a PHP extension
  • Lower memory usage, especially for large files
  • Supports writing Excel files (XLSX format)

Cons of php-ext-xlswriter

  • Requires installation and compilation as a PHP extension
  • Less portable across different environments
  • Steeper learning curve compared to SimpleXLSX

Code Comparison

SimpleXLSX (reading):

$xlsx = SimpleXLSX::parse('file.xlsx');
foreach ($xlsx->rows() as $row) {
    print_r($row);
}

php-ext-xlswriter (writing):

$config = ['path' => './example.xlsx'];
$excel = new \Vtiful\Kernel\Excel($config);
$excel->fileName('tutorial01.xlsx')
    ->header(['name', 'age'])
    ->data([['viest', 21]])
    ->output();

SimpleXLSX is a pure PHP library that focuses on reading XLSX files, making it easy to use and deploy. It's suitable for simpler tasks and environments where installing extensions is not possible.

php-ext-xlswriter is a high-performance PHP extension for both reading and writing Excel files. It's ideal for applications dealing with large datasets or requiring fast processing, but comes with the trade-off of more complex setup and less portability.

Choose SimpleXLSX for ease of use and portability, or php-ext-xlswriter for performance and advanced Excel manipulation capabilities.

11,464

ARCHIVED

Pros of PHPExcel

  • More comprehensive feature set for Excel manipulation
  • Supports a wider range of Excel formats (including older versions)
  • Extensive documentation and community support

Cons of PHPExcel

  • Larger file size and higher memory usage
  • Slower performance, especially with large spreadsheets
  • No longer actively maintained (replaced by PhpSpreadsheet)

Code Comparison

PHPExcel

$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello World');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('myfile.xlsx');

SimpleXLSX

$xlsx = SimpleXLSX::parse('file.xlsx');
foreach ($xlsx->rows() as $row) {
    print_r($row);
}

SimpleXLSX is more focused on reading XLSX files, while PHPExcel offers both reading and writing capabilities. SimpleXLSX is lightweight and faster for basic operations, making it suitable for simpler tasks. PHPExcel, while more resource-intensive, provides a broader range of features for complex Excel manipulations.

The code examples demonstrate the difference in complexity: PHPExcel requires more setup but offers more control, while SimpleXLSX provides a straightforward approach for reading XLSX files.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

SimpleXLSX class (Official)

Parse and retrieve data from Excel XLSx files. MS Excel 2007 workbooks PHP reader. No addiditional extensions need (internal unzip + standart SimpleXML parser).

See also:
SimpleXLS old format MS Excel 97 php reader.
SimpleXLSXGen xlsx php writer.

Hey, bro, please ★ the package for my motivation :) and donate for more motivation!

Sergey Shuchkin sergey.shuchkin@gmail.com

Basic Usage

use Shuchkin\SimpleXLSX;

if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
    print_r( $xlsx->rows() );
} else {
    echo SimpleXLSX::parseError();
}
Array
(
    [0] => Array
        (
            [0] => ISBN
            [1] => title
            [2] => author
            [3] => publisher
            [4] => ctry
        )

    [1] => Array
        (
            [0] => 618260307
            [1] => The Hobbit
            [2] => J. R. R. Tolkien
            [3] => Houghton Mifflin
            [4] => USA
        )

)

Installation

The recommended way to install this library is through Composer. New to Composer?

This will install the latest supported version:

$ composer require shuchkin/simplexlsx

or download PHP 5.5+ class here

Basic methods

// open
SimpleXLSX::parse( $filename, $is_data = false, $debug = false ): SimpleXLSX (or false)
SimpleXLSX::parseFile( $filename, $debug = false ): SimpleXLSX (or false)
SimpleXLSX::parseData( $data, $debug = false ): SimpleXLSX (or false)
// simple
$xlsx->rows($worksheetIndex = 0, $limit = 0): array
$xlsx->readRows($worksheetIndex = 0, $limit = 0): Generator - helps read huge xlsx
$xlsx->toHTML($worksheetIndex = 0, $limit = 0): string
// extended
$xlsx->rowsEx($worksheetIndex = 0, $limit = 0): array
$xlsx->readRowsEx($worksheetIndex = 0, $limit = 0): Generator - helps read huge xlsx with styles
$xlsx->toHTMLEx($worksheetIndex = 0, $limit = 0): string
// meta
$xlsx->dimension($worksheetIndex):array [num_cols, num_rows]
$xlsx->sheetsCount():int
$xlsx->sheetNames():array
$xlsx->sheetName($worksheetIndex):string
$xlsx->sheetMeta($worksheetIndex = null):array sheets metadata (null = all sheets)
$xlsx->isHiddenSheet($worksheetIndex):bool
$xlsx->getStyles():array

Examples

XLSX to html table

echo SimpleXLSX::parse('book.xlsx')->toHTML();

or

if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
	echo '<table border="1" cellpadding="3" style="border-collapse: collapse">';
	foreach( $xlsx->rows() as $r ) {
		echo '<tr><td>'.implode('</td><td>', $r ).'</td></tr>';
	}
	echo '</table>';
} else {
	echo SimpleXLSX::parseError();
}

or styled html table

if ( $xlsx = SimpleXLSX::parse('book_styled.xlsx') ) {
    echo $xlsx->toHTMLEx();
}

XLSX read huge file, xlsx to csv

if ( $xlsx = SimpleXLSX::parse( 'xlsx/books.xlsx' ) ) {
    $f = fopen('book.csv', 'wb');
    // fwrite($f, chr(0xEF) . chr(0xBB) . chr(0xBF)); // UTF-8 BOM
    foreach ( $xlsx->readRows() as $r ) {
        fputcsv($f, $r); // fputcsv($f, $r, ';', '"', "\\", "\r\n");
    }
    fclose($f);
} else {
    echo SimpleXLSX::parseError();
}

XLSX get sheet names and sheet indexes

// Sheet numeration started 0

if ( $xlsx = SimpleXLSX::parse( 'xlsx/books.xlsx' ) ) {
    print_r( $xlsx->sheetNames() );
    print_r( $xlsx->sheetName( $xlsx->activeSheet ) );
}

Array
(
    [0] => Sheet1
    [1] => Sheet2
    [2] => Sheet3
)
Sheet2

Using rowsEx() to extract cell info

$xlsx = SimpleXLSX::parse('book.xlsx');
print_r( $xlsx->rowsEx() );

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [type] => s
                    [name] => A1
                    [value] => ISBN
                    [href] => 
                    [f] => 
                    [format] => 
                    [s] => 0
                    [css] => color: #000000;font-family: Calibri;font-size: 17px;
                    [r] => 1
                    [hidden] =>
                    [width] => 13.7109375
                    [height] => 0
                    [comment] =>
                )
        
            [1] => Array
                (
                    [type] => 
                    [name] => B1
                    [value] => 2016-04-12 13:41:00
                    [href] => Sheet1!A1
                    [f] => 
                    [format] => m/d/yy h:mm
                    [s] => 0
                    [css] => color: #000000;font-family: Calibri;font-size: 17px;            
                    [r] => 2
                    [hidden] => 1
                    [width] => 16.5703125
                    [height] => 0
                    [comment] => Serg: See transaction history   
                    
                )
typecell type
namecell name (A1, B11)
valuecell value (1233, 1233.34, 2022-02-21 00:00:00, String)
hrefinternal and external links
fformula
sstyle index, use $xlsx->cellFormats[ $index ] to get style
cssgenerated cell CSS
rrow index
hiddenhidden row or column
widthwidth in custom units
heightheight in points (pt, 1/72 in)
commentCell comment as plain text

Select Sheet

$xlsx = SimpleXLSX::parse('book.xlsx');
// Sheet numeration started 0, we select second worksheet
foreach( $xlsx->rows(1) as $r ) {
// ...
}

Get sheet by index

$xlsx = SimpleXLSX::parse('book.xlsx');	
echo 'Sheet Name 2 = '.$xlsx->sheetName(1);

XLSX::parse remote data

if ( $xlsx = SimpleXLSX::parse('https://www.example.com/example.xlsx' ) ) {
	$dim = $xlsx->dimension(1); // don't trust dimension extracted from xml
	$num_cols = $dim[0];
	$num_rows = $dim[1];
	echo $xlsx->sheetName(1).':'.$num_cols.'x'.$num_rows;
} else {
	echo SimpleXLSX::parseError();
}

XLSX::parse memory data

// For instance $data is a data from database or cache    
if ( $xlsx = SimpleXLSX::parseData( $data ) ) {
	print_r( $xlsx->rows() );
} else {
	echo SimpleXLSX::parseError();
}

Get Cell (slow)

echo $xlsx->getCell(0, 'B2'); // The Hobbit

DateTime helpers

// default SimpleXLSX datetime format is YYYY-MM-DD HH:MM:SS (ISO, MySQL)
echo $xlsx->getCell(0,'C2'); // 2016-04-12 13:41:00

// custom datetime format
$xlsx->setDateTimeFormat('d.m.Y H:i');
echo $xlsx->getCell(0,'C2'); // 12.04.2016 13:41

// unixstamp
$xlsx->setDateTimeFormat('U');
$ts = $xlsx->getCell(0,'C2'); // 1460468460
echo gmdate('Y-m-d', $ts); // 2016-04-12
echo gmdate('H:i:s', $ts); // 13:41:00

// raw excel value
$xlsx->setDateTimeFormat( NULL ); // returns as excel datetime
$xd = $xlsx->getCell(0,'C2'); // 42472.570138889
echo gmdate('m/d/Y', $xlsx->unixstamp( $xd )); // 04/12/2016
echo gmdate('H:i:s', $xlsx->unixstamp( $xd )); // 13:41:00 

Rows with header values as keys

if ( $xlsx = SimpleXLSX::parse('books.xlsx')) {
    // Produce array keys from the array values of 1st array element
    $header_values = $rows = [];
    foreach ( $xlsx->rows() as $k => $r ) {
        if ( $k === 0 ) {
            $header_values = $r;
            continue;
        }
        $rows[] = array_combine( $header_values, $r );
    }
    print_r( $rows );
}
Array
(
    [0] => Array
        (
            [ISBN] => 618260307
            [title] => The Hobbit
            [author] => J. R. R. Tolkien
            [publisher] => Houghton Mifflin
            [ctry] => USA
        )
    [1] => Array
        (
            [ISBN] => 908606664
            [title] => Slinky Malinki
            [author] => Lynley Dodd
            [publisher] => Mallinson Rendel
            [ctry] => NZ
        )
)

Debug

use Shuchkin\SimpleXLSX;

ini_set('error_reporting', E_ALL );
ini_set('display_errors', 1 );

if ( $xlsx = SimpleXLSX::parseFile('books.xlsx', true ) ) {
    echo $xlsx->toHTML();
} else {
    echo SimpleXLSX::parseError();
}

Classic OOP style

use SimpleXLSX;

$xlsx = new SimpleXLSX('books.xlsx'); // try...catch
if ( $xlsx->success() ) {
    foreach( $xlsx->rows() as $r ) {
        // ...
    }
} else {
    echo 'xlsx error: '.$xlsx->error();
}

More examples here

Error Codes

SimpleXLSX::ParseErrno(), $xlsx->errno()

codemessagecomment
1File not foundWhere file? UFO?
2Unknown archive formatZIP?
3XML-entry parser errorbad XML
4XML-entry not foundbad ZIP archive
5Entry not foundFile not found in ZIP archive
6Worksheet not foundNot exists