Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phpspreadsheet Laravel Package

phpoffice/phpspreadsheet

PhpSpreadsheet is a pure-PHP library for reading and writing spreadsheet files (Excel, LibreOffice Calc, and more). Create, edit, and export workbooks with rich formatting, formulas, and multiple formats via a clean, well-documented API.

View on GitHub
Deep Wiki
Context7

Reading and writing to file

As you already know from the architecture, reading and writing to a persisted storage is not possible using the base PhpSpreadsheet classes. For this purpose, PhpSpreadsheet provides readers and writers, which are implementations of \PhpOffice\PhpSpreadsheet\Reader\IReader and \PhpOffice\PhpSpreadsheet\Writer\IWriter.

\PhpOffice\PhpSpreadsheet\IOFactory

The PhpSpreadsheet API offers multiple methods to create a \PhpOffice\PhpSpreadsheet\Reader\IReader or \PhpOffice\PhpSpreadsheet\Writer\IWriter instance:

Direct creation via \PhpOffice\PhpSpreadsheet\IOFactory. All examples underneath demonstrate the direct creation method. Note that you can also use the \PhpOffice\PhpSpreadsheet\IOFactory class to do this.

Creating \PhpOffice\PhpSpreadsheet\Reader\IReader using \PhpOffice\PhpSpreadsheet\IOFactory

There are 2 methods for reading in a file into PhpSpreadsheet: using automatic file type resolving or explicitly.

Automatic file type resolving checks the different \PhpOffice\PhpSpreadsheet\Reader\IReader distributed with PhpSpreadsheet. If one of them can load the specified file name, the file is loaded using that \PhpOffice\PhpSpreadsheet\Reader\IReader. Explicit mode requires you to specify which \PhpOffice\PhpSpreadsheet\Reader\IReader should be used.

You can create a \PhpOffice\PhpSpreadsheet\Reader\IReader instance using \PhpOffice\PhpSpreadsheet\IOFactory in automatic file type resolving mode using the following code sample:

$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("05featuredemo.xlsx");

A typical use of this feature is when you need to read files uploaded by your users, and you don’t know whether they are uploading xls or xlsx files.

If you need to set some properties on the reader, (e.g. to only read data, see more about this later), then you may instead want to use this variant:

$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("05featuredemo.xlsx");
$reader->setReadDataOnly(true);
$reader->load("05featuredemo.xlsx");

You can create a \PhpOffice\PhpSpreadsheet\Reader\IReader instance using \PhpOffice\PhpSpreadsheet\IOFactory in explicit mode using the following code sample:

$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
$spreadsheet = $reader->load("05featuredemo.xlsx");

Note that automatic type resolving mode is slightly slower than explicit mode.

Creating \PhpOffice\PhpSpreadsheet\Writer\IWriter using \PhpOffice\PhpSpreadsheet\IOFactory

You can create a \PhpOffice\PhpSpreadsheet\Writer\IWriter instance using \PhpOffice\PhpSpreadsheet\IOFactory:

$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
$writer->save("05featuredemo.xlsx");

Excel 2007 (SpreadsheetML) file format

Xlsx file format is the main file format of PhpSpreadsheet. It allows outputting the in-memory spreadsheet to a .xlsx file.

\PhpOffice\PhpSpreadsheet\Reader\Xlsx

Reading a spreadsheet

You can read an .xlsx file using the following code:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load("05featuredemo.xlsx");

Read data only

You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load("05featuredemo.xlsx");

Read specific sheets only

You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$reader->setLoadSheetsOnly(["Sheet 1", "My special sheet"]);
$spreadsheet = $reader->load("05featuredemo.xlsx");

Read specific cells only

You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter.

The following code will only read row 1 and rows 20 – 30 of any sheet in the Excel file:

class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {

    public function readCell($columnAddress, $row, $worksheetName = '') {
        // Read title row and rows 20 - 30
        if ($row == 1 || ($row >= 20 && $row <= 30)) {
            return true;
        }
        return false;
    }
}

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$reader->setReadFilter( new MyReadFilter() );
$spreadsheet = $reader->load("06largescale.xlsx");

Read Filtering does not renumber cell rows and columns. If you filter to read only rows 100-200, cells that you read will still be numbered A100-A200, not A1-A101. Cells A1-A99 will not be loaded, but if you then try to call getCell() for a cell outside your loaded range, then PHPSpreadsheet will create a new cell with a null value.

Methods such as toArray() assume that all cells in a spreadsheet has been loaded from A1, so will return null values for rows and columns that fall outside your filter range: it is recommended that you keep track of the range that your filter has requested, and use rangeToArray() instead.

\PhpOffice\PhpSpreadsheet\Writer\Xlsx

Writing a spreadsheet

You can write an .xlsx file using the following code:

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save("05featuredemo.xlsx");

Formula pre-calculation

By default, this writer pre-calculates all formulas in the spreadsheet. This can be slow on large spreadsheets, and maybe even unwanted. You can however disable formula pre-calculation:

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->setPreCalculateFormulas(false);
$writer->save("05featuredemo.xlsx");

Note Formulas will still be calculated in any column set to be autosized even if pre-calculated is set to false

Note Prior to release 3.7.0, the use of this feature will cause Excel to be used in a mode where opening a sheet saved in this manner might not automatically recalculate a cell's formula when a cell used it the formula changes. Furthermore, that behavior might be applied to all spreadsheets open at the time. To avoid this behavior, add the following statement after setPreCalculateFormulas above:

$writer->setForceFullCalc(false);

Starting with Release 4.0.0, the property's default is changed to false and that statement is no longer be required. The property can be set to null if the old behavior is needed.

Office 2003 compatibility pack

Because of a bug in the Office2003 compatibility pack, there can be some small issues when opening Xlsx spreadsheets (mostly related to formula calculation). You can enable Office2003 compatibility with the following code:

    $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
    $writer->setOffice2003Compatibility(true);
    $writer->save("05featuredemo.xlsx");

Office2003 compatibility option should only be used when needed because it disables several Office2007 file format options, resulting in a lower-featured Office2007 spreadsheet.

Maximum Column Width

In the Xlsx User Interface, the user cannot set a column width > 255. Nevertheless, it will honor a higher value if supplied in the Xml. PhpSpreadsheet will, by default, allow values > 255 to be written. However, Excel's behavior, restricting the value to 255, can be emulated:

    $writer->setRestrictMaxColumnWidth(true);

Form Control Fields

PhpSpreadsheet offers limited support for Forms Controls (buttons, checkboxes, etc.). The support is available only for Excel 2007 format, and is offered solely to allow loading a spreadsheet with such controls and saving it as a new file. Support is not available for adding such elements to the spreadsheet, nor even to locate them to determine their properties (so you can't modify or delete them). Modifications to a worksheet with controls are "caveat emptor"; some modifications will work correctly, but others are very likely to cause problems, e.g. adding a comment to the worksheet, or inserting or deleting rows or columns in a manner that would cause the controls to change location.

Excel 5 (BIFF) file format

Xls file format is the old Excel file format, implemented in PhpSpreadsheet to provide a uniform manner to create both .xlsx and .xls files. It is basically a modified version of PEAR Spreadsheet_Excel_Writer, although it has been extended and has fewer limitations and more features than the old PEAR library. This can read all BIFF versions that use OLE2: BIFF5 (introduced with office 95) through BIFF8, but cannot read earlier versions.

Xls file format will not be developed any further, it just provides an additional file format for PhpSpreadsheet.

Excel5 (BIFF) limitations Please note that BIFF file format has some limits regarding to styling cells and handling large spreadsheets via PHP.

\PhpOffice\PhpSpreadsheet\Reader\Xls

Reading a spreadsheet

You can read an .xls file using the following code:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$spreadsheet = $reader->load("05featuredemo.xls");

Read data only

You can set the option setReadDataOnly on the reader, to instruct the reader to ignore styling, data validation, … and just read cell data:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load("05featuredemo.xls");

Read specific sheets only

You can set the option setLoadSheetsOnly on the reader, to instruct the reader to only load the sheets with a given name:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$reader->setLoadSheetsOnly(["Sheet 1", "My special sheet"]);
$spreadsheet = $reader->load("05featuredemo.xls");

Read specific cells only

You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter.

The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file:

class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {

    public function readCell($columnAddress, $row, $worksheetName = '') {
        // Read title row and rows 20 - 30
        if ($row == 1 || ($row >= 20 && $row <= 30)) {
            return true;
        }
        return false;
    }
}

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$reader->setReadFilter( new MyReadFilter() );
$spreadsheet = $reader->load("06largescale.xls");

\PhpOffice\PhpSpreadsheet\Writer\Xls

Writing a spreadsheet

You can write an .xls file using the following code:

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xls($spreadsheet);
$writer->save("05featuredemo.xls");

Excel 2003 XML file format

Excel 2003 XML file format is a file format which can be used in older versions of Microsoft Excel.

Excel 2003 XML limitations Please note that Excel 2003 XML format has some limits regarding to styling cells and handling large spreadsheets via PHP.

\PhpOffice\PhpSpreadsheet\Reader\Xml

Reading a spreadsheet

You can read an Excel 2003 .xml file using the following code:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xml();
$spreadsheet = $reader->load("05featuredemo.xml");

Read specific cells only

You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter.

The following code will only read row 1 and rows 20 to 30 of any sheet in the Excel file:

class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {

    public function readCell($columnAddress, $row, $worksheetName = '') {
        // Read title row and rows 20 - 30
        if ($row == 1 || ($row >= 20 && $row <= 30)) {
            return true;
        }
        return false;
    }

}

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xml();
$reader->setReadFilter( new MyReadFilter() );
$spreadsheet = $reader->load("06largescale.xml");

Symbolic LinK (SYLK)

Symbolic Link (SYLK) is a Microsoft file format typically used to exchange data between applications, specifically spreadsheets. SYLK files conventionally have a .slk suffix. Composed of only displayable ANSI characters, it can be easily created and processed by other applications, such as databases.

SYLK limitations Please note that SYLK file format has some limits regarding to styling cells and handling large spreadsheets via PHP.

\PhpOffice\PhpSpreadsheet\Reader\Slk

Reading a spreadsheet

You can read an .slk file using the following code:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Slk();
$spreadsheet = $reader->load("05featuredemo.slk");

Read specific cells only

You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter.

The following code will only read row 1 and rows 20 to 30 of any sheet in the SYLK file:

class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {

    public function readCell($columnAddress, $row, $worksheetName = '') {
        // Read title row and rows 20 - 30
        if ($row == 1 || ($row >= 20 && $row <= 30)) {
            return true;
        }
        return false;
    }

}

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Slk();
$reader->setReadFilter( new MyReadFilter() );
$spreadsheet = $reader->load("06largescale.slk");

Open/Libre Office (.ods)

Open Office or Libre Office .ods files are the standard file format for Open Office or Libre Office Calc files.

\PhpOffice\PhpSpreadsheet\Reader\Ods

Reading a spreadsheet

You can read an .ods file using the following code:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Ods();
$spreadsheet = $reader->load("05featuredemo.ods");

Read specific cells only

You can set the option setReadFilter on the reader, to instruct the reader to only load the cells which match a given rule. A read filter can be any class which implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter. By default, all cells are read using the \PhpOffice\PhpSpreadsheet\Reader\DefaultReadFilter.

The following code will only read row 1 and rows 20 to 30 of any sheet in the Calc file:

class MyReadFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter {

    public function readCell($columnAddress, $row, $worksheetName = '') {
        // Read title row and rows 20 - 30
        if ($row == 1 || ($row >= 20 && $row <= 30)) {
            return true;
        }
        return false;
    }

}

$reader = new PhpOffice\PhpSpreadsheet\Reader\Ods();
$reader->setReadFilter( new MyReadFilter() );
$spreadsheet = $reader->load("06largescale.ods");

CSV (Comma Separated Values)

CSV (Comma Separated Values) are often used as an import/export file format with other systems. PhpSpreadsheet allows reading and writing to CSV files.

CSV limitations Please note that CSV file format has some limits regarding to styling cells, number formatting, ...

\PhpOffice\PhpSpreadsheet\Reader\Csv

Reading a CSV file

You can read a .csv file using the following code:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
$spreadsheet = $reader->load('sample.csv');

You can also treat a string as if it were the contents of a CSV file as follows:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
$spreadsheet = $reader->loadSpreadsheetFromString($data);

Setting CSV options

Often, CSV files are not really "comma separated", or use semicolon (;) as a separator. You can set some options before reading a CSV file.

The separator will be auto-detected, so in most cases it should not be necessary to specify it. But in cases where auto-detection does not fit the use-case, then it can be set manually.

Note that \PhpOffice\PhpSpreadsheet\Reader\Csv by default assumes that the loaded CSV file is UTF-8 encoded. If you are reading CSV files that were created in Microsoft Office Excel the correct input encoding may rather be Windows-1252 (CP1252). Always make sure that the input encoding is set appropriately.

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
$reader->setInputEncoding('CP1252');
$reader->setDelimiter(';');
$reader->setEnclosure('');
$reader->setSheetIndex(0);

$spreadsheet = $reader->load("sample.csv");

You may also let PhpSpreadsheet attempt to guess the input encoding. It will do so based on a test for BOM (UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, or UTF-32LE), or by doing heuristic tests for those encodings, falling back to a specifiable encoding (default is CP1252) if all of those tests fail.

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
$encoding = \PhpOffice\PhpSpreadsheet\Reader\Csv::guessEncoding('sample.csv');
// or, e.g. $encoding = \PhpOffice\PhpSpreadsheet\Reader\Csv::guessEncoding(
//                      'sample.csv', 'ISO-8859-2');
$reader->setInputEncoding($encoding);
$reader->setDelimiter(';');
$reader->setEnclosure('');
$reader->setSheetIndex(0);

$spreadsheet = $reader->load('sample.csv');

You can also set the reader to guess the encoding rather than calling guessEncoding directly. In this case, the user-settable fallback encoding is used if nothing else works.

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
$reader->setInputEncoding(\PhpOffice\PhpSpreadsheet\Reader\Csv::GUESS_ENCODING);
$reader->setFallbackEncoding('ISO-8859-2');  // default CP1252 without this statement
$reader->setDelimiter(';');
$reader->setEnclosure('');
$reader->setSheetIndex(0);

$spreadsheet = $reader->load('sample.csv');

The CSV reader will normally not load null strings into the spreadsheet. To load them:

$reader->setPreserveNullString(true);

You can set a callback to be invoked when the constructor is executed, either through new Csv() or IOFactory::load, and have that callback set the customizable attributes to whatever defaults are appropriate for your environment.

function constructorCallback(\PhpOffice\PhpSpreadsheet\Reader\Csv $reader): void
{
    $reader->setInputEncoding(\PhpOffice\PhpSpreadsheet\Reader\Csv::GUESS_ENCODING);
    $reader->setFallbackEncoding('ISO-8859-2');
    $reader->setDelimiter(',');
    $reader->setEnclosure('"');
    // Following represents how Excel behaves better than the default escape character
    $reader->setEscapeCharacter('');
}

\PhpOffice\PhpSpreadsheet\Reader\Csv::setConstructorCallback('constructorCallback');
$spreadsheet = \PhpSpreadsheet\IOFactory::load('sample.csv');

As a (probably better) alternative, you can extend the Reader\Csv class to have whatever default properties you want, and use the extended class with new. For use with IOFactory, you can register the extended class as the Csv Reader:

IOFactory::registerReader(IOFactory::READER_CSV, Reader\CsvNoEscape::class);

Starting with release 5.6, the IOFactory methods createReader, load, identify, and createReaderForFile also allow you to specify the appropriate reader for a file type, without having to register the class or affecting the ability of IOFactory to find classes suitable for files in other formats.

$spreadsheet = IOFactory::load(
    $inputFileName,
    mergeArray: [IOFactory::READER_CSV => Reader\CsvNoEscape::class]
    /* or mergeArray: IOFactory::USE_CSV_NO_EXCAPE */
);

Finally, note the use of Reader\CsvNoEscape above. That class, which extends Reader\Csv, is introduced in release 5.6. Php long ago defined its own escaping mechanism for Csv files; this is completely non-portable, and was deprecated in Php8.4 and will go away with Php9. Likewise, the ability to auto-detect Mac line endings will go away in Php9. CsvNoEscape sets the escape character to null-string (the only value supported for Php9), sets auto-detection of Mac endings to false, and will throw an exception if the user attempts to change either. Reader\CsvNoEscape is unquestionably a better choice for new applications than Reader\Csv.

Read a specific worksheet

CSV files can only contain one worksheet. Therefore, you can specify which sheet to read from CSV:

$reader->setSheetIndex(0);

Read into existing spreadsheet

When working with CSV files, it might occur that you want to import CSV data into an existing Spreadsheet object. The following code loads a CSV file into an existing $spreadsheet containing some sheets, and imports onto the 6th sheet:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
$reader->setDelimiter(';');
$reader->setEnclosure('"');
$reader->setSheetIndex(5);

$reader->loadIntoExisting("05featuredemo.csv", $spreadsheet);

Line endings

Line endings for Unix (\n) and Windows (\r\n) are supported.

Support for Mac line endings (\r) is deprecated since PHP 8.1, and is scheduled to remain deprecated for all later PHP8 releases; PhpSpreadsheet will continue to support them...

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport