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
.
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.
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.
You can create a \PhpOffice\PhpSpreadsheet\Writer\IWriter
instance using
\PhpOffice\PhpSpreadsheet\IOFactory
:
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, "Xlsx");
$writer->save("05featuredemo.xlsx");
Xlsx file format is the main file format of PhpSpreadsheet. It allows outputting the in-memory spreadsheet to a .xlsx file.
You can read an .xlsx file using the following code:
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load("05featuredemo.xlsx");
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");
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");
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.
You can write an .xlsx file using the following code:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
$writer->save("05featuredemo.xlsx");
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.
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.
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.
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.
You can read an .xls file using the following code:
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls();
$spreadsheet = $reader->load("05featuredemo.xls");
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");
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");
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");
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 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.
You can read an Excel 2003 .xml file using the following code:
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xml();
$spreadsheet = $reader->load("05featuredemo.xml");
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) 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.
You can read an .slk file using the following code:
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Slk();
$spreadsheet = $reader->load("05featuredemo.slk");
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 Office or Libre Office .ods files are the standard file format for Open Office or Libre Office Calc files.
You can read an .ods file using the following code:
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Ods();
$spreadsheet = $reader->load("05featuredemo.ods");
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) 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, ...
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);
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);
Finally, 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');
CSV files can only contain one worksheet. Therefore, you can specify which sheet to read from CSV:
$reader->setSheetIndex(0);
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 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 for PHP 8.*.
Support is scheduled to be dropped with PHP 9;
PhpSpreadsheet will then no longer handle CSV files
with Mac line endings correctly.
You can suppress testing for Mac line endings as follows:
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
$reader->setTestAutoDetect(false);
Starting with Release 4.0.0, the property defaults to false
,
so the statement above is no longer needed. The old behavior
can be enabled by setting the property to true
.
You can write a .csv file using the following code:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
$writer->save("05featuredemo.csv");
Often, CSV files are not really "comma separated", or use semicolon (;
)
as a separator. You can set some options before writing a CSV
file:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
$writer->setDelimiter(';');
$writer->setEnclosure('"');
$writer->setLineEnding("\r\n");
$writer->setSheetIndex(0);
$writer->save("05featuredemo.csv");
By default, all CSV fields are wrapped in the enclosure character, which defaults to double-quote. You can change to use the enclosure character only when required:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
$writer->setEnclosureRequired(false);
$writer->save("05featuredemo.csv");
CSV files can only contain one worksheet. Therefore, you can specify which sheet to write to CSV:
$writer->setSheetIndex(0);
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\Csv($spreadsheet);
$writer->setPreCalculateFormulas(false);
$writer->save("05featuredemo.csv");
CSV files are written in UTF-8. If they do not contain characters outside the ASCII range, nothing else need be done. However, if such characters are in the file, or if the file starts with the 2 characters 'ID', it should explicitly include a BOM file header; if it doesn't, Excel will not interpret those characters correctly. This can be enabled by using the following code:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
$writer->setUseBOM(true);
$writer->save("05featuredemo.csv");
It can be set to output with the encoding that can be specified by PHP's mb_convert_encoding. This looks like the following code:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
$writer->setUseBOM(false);
$writer->setOutputEncoding('SJIS-WIN');
$writer->save("05featuredemo.csv");
A CSV file can have a different number of columns in each row. This differs from the default behavior when saving as a .csv in Excel, but can be enabled in PhpSpreadsheet by using the following code:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
$writer->setVariableColumns(true);
$writer->save("05featuredemo.csv");
If the worksheet you are exporting contains numbers with decimal or thousands separators then you should think about what characters you want to use for those before doing the export.
By default PhpSpreadsheet looks up in the server's locale settings to decide what characters to use. But to avoid problems it is recommended to set the characters explicitly as shown below.
English users will want to use this before doing the export:
\PhpOffice\PhpSpreadsheet\Shared\StringHelper::setDecimalSeparator('.');
\PhpOffice\PhpSpreadsheet\Shared\StringHelper::setThousandsSeparator(',');
German users will want to use the opposite values.
\PhpOffice\PhpSpreadsheet\Shared\StringHelper::setDecimalSeparator(',');
\PhpOffice\PhpSpreadsheet\Shared\StringHelper::setThousandsSeparator('.');
Note that the above code sets decimal and thousand separators as global options. This also affects how HTML and PDF is exported.
PhpSpreadsheet allows you to read or write a spreadsheet as HTML format, for quick representation of the data in it to anyone who does not have a spreadsheet application on their PC, or loading files saved by other scripts that simply create HTML markup and give it a .xls file extension.
HTML limitations Please note that HTML file format has some limits regarding to styling cells, number formatting, ... Declared charsets compatible with ASCII in range 00-7F, and UTF-8/16 with BOM are supported.
You can read an .html or .htm file using the following code:
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
$spreadsheet = $reader->load("05featuredemo.html");
HTML limitations Please note that HTML reader is still experimental and does not yet support merged cells or nested tables cleanly
Please note that \PhpOffice\PhpSpreadsheet\Writer\Html
only outputs the
first worksheet by default.
You can write a .htm file using the following code:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($spreadsheet);
$writer->save("05featuredemo.htm");
HTML files can contain one or more worksheets. If you want to write all sheets into a single HTML file, use the following code:
$writer->writeAllSheets();
HTML files can contain one or more worksheets. Therefore, you can specify which sheet to write to HTML:
$writer->setSheetIndex(0);
There might be situations where you want to explicitly set the included images root. For example, instead of:
<img src="./images/logo.jpg">
You might want to see:
<img src="http://www.domain.com/images/logo.jpg">
You can use the following code to achieve this result:
$writer->setImagesRoot('http://www.example.com');
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\Html($spreadsheet);
$writer->setPreCalculateFormulas(false);
$writer->save("05featuredemo.htm");
There might be a situation where you want to embed the generated HTML in an existing website. \PhpOffice\PhpSpreadsheet\Writer\Html provides support to generate only specific parts of the HTML code, which allows you to use these parts in your website.
Supported methods:
generateHTMLHeader()
generateStyles()
generateSheetData()
generateHTMLFooter()
generateHTMLAll()
Here's an example which retrieves all parts independently and merges them into a resulting HTML page:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($spreadsheet);
$hdr = $writer->generateHTMLHeader();
$sty = $writer->generateStyles(false); // do not write <style> and </style>
$newstyle = <<<EOF
<style type='text/css'>
$sty
body {
background-color: yellow;
}
</style>
EOF;
echo preg_replace('@</head>@', "$newstyle\n</head>", $hdr);
echo $writer->generateSheetData();
echo $writer->generateHTMLFooter();
You can also add a callback function to edit the generated html before saving. For example, you could change the gridlines from a thin solid black line:
function changeGridlines(string $html): string
{
return str_replace('{border: 1px solid black;}',
'{border: 2px dashed red;}',
$html);
}
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Html($spreadsheet);
$writer->setEditHtmlCallback('changeGridlines');
$writer->save($filename);
See section \PhpOffice\PhpSpreadsheet\Writer\Csv
how to control the
appearance of these.
PhpSpreadsheet allows you to write a spreadsheet into PDF format, for fast distribution of represented data.
PDF limitations Please note that PDF file format has some limits regarding to styling cells, number formatting, ...
PhpSpreadsheet’s PDF Writer is a wrapper for a 3rd-Party PDF Rendering library such as TCPDF, mPDF or Dompdf. You must now install a PDF rendering library yourself; but PhpSpreadsheet will work with a number of different libraries.
Currently, the following libraries are supported:
Library | Downloadable from | PhpSpreadsheet writer |
---|---|---|
TCPDF | https://github.com/tecnickcom/tcpdf | Tcpdf |
mPDF | https://github.com/mpdf/mpdf | Mpdf |
Dompdf | https://github.com/dompdf/dompdf | Dompdf |
The different libraries have different strengths and weaknesses. Some generate better formatted output than others, some are faster or use less memory than others, while some generate smaller .pdf files. It is the developers choice which one they wish to use, appropriate to their own circumstances.
You can instantiate a writer with its specific name, like so:
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Mpdf');
Or you can register which writer you are using with a more generic name, so you don't need to remember which library you chose, only that you want to write PDF files:
$class = \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf::class;
\PhpOffice\PhpSpreadsheet\IOFactory::registerWriter('Pdf', $class);
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Pdf');
Or you can instantiate directly the writer of your choice like so:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
If you need a custom implementation, or custom configuration, of a supported PDF library. You can extends the PDF library, and the PDF writer like so:
class My_Custom_TCPDF extends TCPDF
{
// ...
}
class My_Custom_TCPDF_Writer extends \PhpOffice\PhpSpreadsheet\Writer\Pdf\Tcpdf
{
protected function createExternalWriterInstance($orientation, $unit, $paperSize)
{
$instance = new My_Custom_TCPDF($orientation, $unit, $paperSize);
// more configuration of $instance
return $instance;
}
}
\PhpOffice\PhpSpreadsheet\IOFactory::registerWriter('Pdf', MY_TCPDF_WRITER::class);
Once you have identified the Renderer that you wish to use for PDF generation, you can write a .pdf file using the following code:
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf($spreadsheet);
$writer->save("05featuredemo.pdf");
Please note that \PhpOffice\PhpSpreadsheet\Writer\Pdf
only outputs the
first worksheet by default.
PDF files can contain one or more worksheets. If you want to write all sheets into a single PDF file, use the following code:
$writer->writeAllSheets();
PDF files can contain one or more worksheets. Therefore, you can specify which sheet to write to PDF:
$writer->setSheetIndex(0);
PhpSpreadsheet will attempt to honor the orientation and paper size specified in the worksheet for each page it prints, if the renderer supports that. However, you can set all pages to have the same orientation and paper size, e.g.
$writer->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);
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\Pdf\Mpdf($spreadsheet);
$writer->setPreCalculateFormulas(false);
$writer->save("05featuredemo.pdf");
You can also add a callback function to edit the html used to generate the Pdf before saving. See under Html.
See section \PhpOffice\PhpSpreadsheet\Writer\Csv
how to control the
appearance of these.
Readers and writers are the tools that allow you to generate Excel files from templates. This requires less coding effort than generating the Excel file from scratch, especially if your template has many styles, page setup properties, headers etc.
Here is an example how to open a template file, fill in a couple of fields and save it again:
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load('template.xlsx');
$worksheet = $spreadsheet->getActiveSheet();
$worksheet->getCell('A1')->setValue('John');
$worksheet->getCell('A2')->setValue('Smith');
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('write.xls');
Notice that it is ok to load an xlsx file and generate an xls file.
If you are generating an Excel file from pre-rendered HTML content you can do so automatically using the HTML Reader. This is most useful when you are generating Excel files from web application content that would be downloaded/sent to a user.
For example:
$htmlString = '<table>
<tr>
<td>Hello World</td>
</tr>
<tr>
<td>Hello<br />World</td>
</tr>
<tr>
<td>Hello<br>World</td>
</tr>
</table>';
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
$spreadsheet = $reader->loadFromString($htmlString);
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('write.xls');
Suppose you have multiple worksheets you'd like created from html. This can be accomplished as follows.
$firstHtmlString = '<table>
<tr>
<td>Hello World</td>
</tr>
</table>';
$secondHtmlString = '<table>
<tr>
<td>Hello World</td>
</tr>
</table>';
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Html();
$spreadsheet = $reader->loadFromString($firstHtmlString);
$reader->setSheetIndex(1);
$spreadhseet = $reader->loadFromString($secondHtmlString, $spreadsheet);
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('write.xls');
Some Readers and Writers support special "Feature Flags" that need to be explicitly enabled. An example of this is Charts in a spreadsheet. By default, when you load a spreadsheet that contains Charts, the charts will not be loaded. If all you want to do is read the data in the spreadsheet, then loading charts is an overhead for both speed of loading and memory usage. However, there are times when you may want to load any charts in the spreadsheet as well as the data. To do so, you need to tell the Reader explicitly to include Charts.
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("05featuredemo.xlsx");
$reader->setIncludeCharts(true);
$reader->load("spreadsheetWithCharts.xlsx");
Alternatively, you can specify this in the call to load the spreadsheet:
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("spreadsheetWithCharts.xlsx");
$reader->load("spreadsheetWithCharts.xlsx", $reader::LOAD_WITH_CHARTS);
If you wish to use the IOFactory load()
method rather than instantiating a specific Reader, then you can still pass these flags.
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("spreadsheetWithCharts.xlsx", \PhpOffice\PhpSpreadsheet\Reader\IReader::LOAD_WITH_CHARTS);
Flags that are available that can be passed to the Reader in this way include:
- $reader::LOAD_WITH_CHARTS
- $reader::READ_DATA_ONLY
- $reader::IGNORE_EMPTY_CELLS
- $reader::IGNORE_ROWS_WITH_NO_CELLS
Readers | LOAD_WITH_CHARTS | READ_DATA_ONLY | IGNORE_EMPTY_CELLS | IGNORE_ROWS_WITH_NO_CELLS |
---|---|---|---|---|
Xlsx | YES | YES | YES | YES |
Xls | NO | YES | YES | NO |
Xml | NO | NO | NO | NO |
Ods | NO | YES | NO | NO |
Gnumeric | NO | YES | NO | NO |
Html | N/A | N/A | N/A | N/A |
Slk | N/A | NO | NO | NO |
Csv | N/A | NO | NO | NO |
Likewise, when saving a file using a Writer, loaded charts will not be saved unless you explicitly tell the Writer to include them:
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->setIncludeCharts(true);
$writer->save('mySavedFileWithCharts.xlsx');
As with the load()
method, you can also pass flags in the save()
method:
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('mySavedFileWithCharts.xlsx', \PhpOffice\PhpSpreadsheet\Writer\IWriter::SAVE_WITH_CHARTS);
Flags that are available that can be passed to the Reader in this way include:
- $reader::SAVE_WITH_CHARTS
- $reader::DISABLE_PRECALCULATE_FORMULAE
Writers | SAVE_WITH_CHARTS | DISABLE_PRECALCULATE_FORMULAE |
---|---|---|
Xlsx | YES | YES |
Xls | NO | NO |
Ods | NO | YES |
Html | YES | YES |
YES | YES | |
Csv | N/A | YES |
One benefit of flags is that you can pass several flags in a single method call.
Two or more flags can be passed together using PHP's |
operator.
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile('myExampleFile.xlsx');
$reader->load(
'spreadsheetWithCharts.xlsx',
$reader::READ_DATA_ONLY | $reader::IGNORE_EMPTY_CELLS
);
Although not really a spreadsheet format, it can be useful to write data in grid format to a plaintext file. Code like the following can be used:
$array = $sheet->toArray(null, true, true, true);
$textGrid = new \PhpOffice\PhpSpreadsheet\Shared\TextGrid(
$array,
true, // true for cli, false for html
// Starting with release 4.2,
// the output format can be tweaked by uncommenting
// any of the following 3 optional parameters.
// rowDividers: true,
// rowHeaders: false,
// columnHeaders: false,
);
$result = $textGrid->render();
You can then echo $result
to a terminal, or write it to a file with file_put_contents
. The result will resemble:
+-----+------------------+---+----------+
| A | B | C | D |
+---+-----+------------------+---+----------+
| 1 | 6 | 1900-01-06 00:00 | | 0.572917 |
| 2 | 6 | TRUE | | 1<>2 |
| 3 | xyz | xyz | | |
+---+-----+------------------+---+----------+
Please note that this may produce sub-optimal results for situations such as:
- use of accents as combining characters rather than using pre-composed characters (may be handled by extending the class to override the
getString
orstrlen
methods) - Fullwidth characters
- right-to-left characters (better display in a browser than a terminal on a non-RTL system)
- multi-line strings