Update documentation for 3.0

This commit is contained in:
Adrien Loison 2019-05-17 13:12:49 +02:00
parent e8693834a0
commit 0b50f323d8
10 changed files with 190 additions and 101 deletions

View File

@ -16,7 +16,12 @@
<a class="page-link" href="{{ site.github.url }}/docs/">Documentation</a>
<a class="page-link" href="{{ site.github.url }}/guides/">Guides</a>
<a class="page-link" href="{{ site.github.url }}/faq/">FAQ</a>
<a class="page-link" href="https://github.com/box/spout">GitHub</a>
<a class="page-link" href="https://github.com/box/spout">
GitHub
<svg width="12" height="12">
<image xlink:href="/images/external-link.svg" src="/images/external-link.png" width="12" height="12"/>
</svg>
</a>
{% if site.algolia.enabled %}
<span class="site-search">
<input type="text" id="algolia-doc-search">

View File

@ -10,9 +10,8 @@ It is possible to configure both the CSV reader and writer to adapt them to your
```php
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Common\Type;
$reader = ReaderEntityFactory::createReader(Type::CSV);
$reader = ReaderEntityFactory::createReaderFromFile('/path/to/file.csv');
/** All of these methods have to be called before opening the reader. */
$reader->setFieldDelimiter('|');
$reader->setFieldEnclosure('@');
@ -30,10 +29,8 @@ It is however possible to not include the BOM:
```php
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Box\Spout\Common\Type;
$writer = WriterEntityFactory::createWriter(Type::CSV);
$writer = WriterEntityFactory::createWriterFromFile('/path/to/file.csv');
$writer->setShouldAddBOM(false);
```
@ -89,7 +86,7 @@ $writer->setShouldUseInlineStrings(false); // will use shared strings
### Date/Time formatting
When reading a spreadsheet containing dates or times, {{ site.spout_html }} returns the values by default as DateTime objects.
When reading a spreadsheet containing dates or times, {{ site.spout_html }} returns the values by default as `DateTime` objects.
It is possible to change this behavior and have a formatted date returned instead (e.g. "2016-11-29 1:22 AM"). The format of the date corresponds to what is specified in the spreadsheet.
```php
@ -100,11 +97,44 @@ $reader = ReaderEntityFactory::createReader(Type::XLSX);
$reader->setShouldFormatDates(false); // default value
$reader->setShouldFormatDates(true); // will return formatted dates
```
## Empty rows
By default, when {{ site.spout_html }} reads a spreadsheet it skips empty rows and only return rows containing data.
This behavior can be changed so that {{ site.spout_html }} returns all rows:
```php
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
$reader = ReaderEntityFactory::createReaderFromFile('/path/to/file.ext');
$reader->setShouldPreserveEmptyRows(true);
```
## Styling rows
## Styling
It is possible to apply some formatting options to a row. {{ site.spout_html }} supports fonts, background, borders as well as alignment styles.
### Available styles
{{ site.spout_html }} supports styling at a row and cell level. It is possible to customize the fonts, backgrounds, alignment as well as borders.
For fonts and alignments, {{ site.spout_html }} does not support all the possible formatting options yet. But you can find the most important ones:
| Category | Property | API
|:----------|:--------------|:--------------------------------------
| Font | Bold | `StyleBuilder::setFontBold()`
| | Italic | `StyleBuilder::setFontItalic()`
| | Underline | `StyleBuilder::setFontUnderline()`
| | Strikethrough | `StyleBuilder::setFontStrikethrough()`
| | Font name | `StyleBuilder::setFontName('Arial')`
| | Font size | `StyleBuilder::setFontSize(14)`
| | Font color | `StyleBuilder::setFontColor(Color::BLUE)`<br>`StyleBuilder::setFontColor(Color::rgb(0, 128, 255))`
| Alignment | Wrap text | `StyleBuilder::setShouldWrapText(true|false)`
### Styling rows
It is possible to apply some formatting options to a row. In this case, all cells of the row will have the same style:
```php
use Box\Spout\Common\Type;
@ -124,14 +154,8 @@ $style = (new StyleBuilder())
->setBackgroundColor(Color::YELLOW)
->build();
$cells = [
WriterEntityFactory::createCell('Carl'),
WriterEntityFactory::createCell('is'),
WriterEntityFactory::createCell('great!'),
];
/** Create a row with cells and the style*/
$row = WriterEntityFactory::createRow($cells, $style);
/** Create a row with cells and apply the style to all cells */
$row = WriterEntityFactory::createRowFromArray(['Carl', 'is', 'great'], $style);
/** Add the row to the writer */
$writer->addRow($row);
@ -159,41 +183,15 @@ $style = (new StyleBuilder())
$writer = WriterEntityFactory::createWriter(Type::XLSX);
$writer->openToFile($filePath);
$row = WriterEntityFactory::createRowFromArray(['Border Bottom Green Thin Dashed']);
$cells = WriterEntityFactory::createCell('Border Bottom Green Thin Dashed');
$row = WriterEntityFactory::createRow($cells);
$row->setStyle($style);
$writer->addRow($row);
$writer->close();
```
{{ site.spout_html }} will use a default style for all created rows. This style can be overridden this way:
```php
$defaultStyle = (new StyleBuilder())
->setFontName('Arial')
->setFontSize(11)
->build();
$writer = WriterEntityFactory::createWriter(Type::XLSX);
$writer->setDefaultRowStyle($defaultStyle)
->openToFile($filePath);
```
Unfortunately, {{ site.spout_html }} does not support all the possible formatting options yet. But you can find the most important ones:
| Category | Property | API
|:----------|:--------------|:--------------------------------------
| Font | Bold | `StyleBuilder::setFontBold()`
| | Italic | `StyleBuilder::setFontItalic()`
| | Underline | `StyleBuilder::setFontUnderline()`
| | Strikethrough | `StyleBuilder::setFontStrikethrough()`
| | Font name | `StyleBuilder::setFontName('Arial')`
| | Font size | `StyleBuilder::setFontSize(14)`
| | Font color | `StyleBuilder::setFontColor(Color::BLUE)`<br>`StyleBuilder::setFontColor(Color::rgb(0, 128, 255))`
| Alignment | Wrap text | `StyleBuilder::setShouldWrapText(true|false)`
## Styling cells
### Styling cells
The same styling techniques as described in [Styling rows](#styling-rows) can be applied to individual cells of a row as well.
@ -244,6 +242,22 @@ $writer->addRow($row);
$writer->close();
```
### Default style
{{ site.spout_html }} will use a default style for all created rows. This style can be overridden this way:
```php
$defaultStyle = (new StyleBuilder())
->setFontName('Arial')
->setFontSize(11)
->build();
$writer = WriterEntityFactory::createWriter(Type::XLSX);
$writer->setDefaultRowStyle($defaultStyle)
->openToFile($filePath);
```
## Playing with sheets
When creating a XLSX or ODS file, it is possible to control which sheet the data will be written into. At any time, you can retrieve or set the current sheet:
@ -264,14 +278,18 @@ It is also possible to retrieve all the sheets currently created:
$sheets = $writer->getSheets();
```
If you rely on the sheet's name in your application, you can access it and customize it this way:
It is possible to retrieve some sheet's attributes when reading:
```php
// Accessing the sheet name when reading
foreach ($reader->getSheetIterator() as $sheet) {
$sheetName = $sheet->getName();
$isSheetVisible = $sheet->isVisible();
$isSheetActive = $sheet->isActive(); // active sheet when spreadsheet last saved
}
```
If you rely on the sheet's name in your application, you can customize it this way:
```php
// Accessing the sheet name when writing
$sheet = $writer->getCurrentSheet();
$sheetName = $sheet->getName();
@ -290,16 +308,6 @@ $sheet->setName('My custom name');
>
> Handling these restrictions is the developer's responsibility. {{ site.spout_html }} does not try to automatically change the sheet's name, as one may rely on this name to be exactly what was passed in.
Finally, it is possible to know which sheet was active when the spreadsheet was last saved. This can be useful if you are only interested in processing the one sheet that was last focused.
```php
foreach ($reader->getSheetIterator() as $sheet) {
// only process data for the active sheet
if ($sheet->isActive()) {
// do something...
}
}
```
## Fluent interface
@ -307,9 +315,8 @@ Because fluent interfaces are great, you can use them with {{ site.spout_html }}
```php
use Box\Spout\Writer\WriterEntityFactory;
use Box\Spout\Common\Type;
$writer = WriterEntityFactory::create(Type::XLSX);
$writer = WriterEntityFactory::createWriterFromFile('path/to/file.ext');
$writer->setTempFolder($customTempFolderPath)
->setShouldUseInlineStrings(true)
->openToFile($filePath)

View File

@ -49,17 +49,16 @@ Regardless of the file type, the interface to read a file is always the same:
```php
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Common\Type;
$reader = ReaderEntityFactory::createReader(Type::XLSX); // for XLSX files
// $reader = ReaderEntityFactory::createReader(Type::ODS); // for ODS files
// $reader = ReaderEntityFactory::createReader(Type::CSV); // for CSV files
$reader = ReaderEntityFactory::createReaderFromFile('/path/to/file.ext');
$reader->open($filePath);
foreach ($reader->getSheetIterator() as $sheet) {
foreach ($sheet->getRowIterator() as $row) {
// do stuff with the row
$cells = $row->getCells();
...
}
}
@ -68,15 +67,17 @@ $reader->close();
If there are multiple sheets in the file, the reader will read all of them sequentially.
---
In addition to passing a reader type to ```ReaderEntityFactory::createReader```, it is also possible to provide a path to a file and create the reader.
Note that {{ site.spout_html }} guesses the reader type based on the file extension. If the extension is not standard (`.csv`, `.ods`, `.xlsx` _- lower/uppercase_), the reader type needs to be specified:
```php
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Common\Type;
$reader = ReaderEntityFactory::createReaderFromFile('/path/to/file.xlsx');
$reader = ReaderEntityFactory::createReader(Type::XLSX); // for XLSX files
// $reader = ReaderEntityFactory::createReader(Type::ODS); // for ODS files
// $reader = ReaderEntityFactory::createReader(Type::CSV); // for CSV files
```
### Writer
@ -86,16 +87,12 @@ As with the reader, there is one common interface to write data to a file:
```php
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Box\Spout\Common\Entity\Row;
use Box\Spout\Common\Type;
$writer = WriterEntityFactory::createWriter(Type::XLSX);
// $writer = WriterEntityFactory::createWriter(Type::ODS);
// $writer = WriterEntityFactory::createWriter(Type::CSV);
$reader = ReaderEntityFactory::createReaderFromFile('/path/to/file.ext');
$writer->openToFile($filePath); // write data to a file or to a PHP stream
//$writer->openToBrowser($fileName); // stream data directly to the browser
$cells = [
WriterEntityFactory::createCell('Carl'),
WriterEntityFactory::createCell('is'),
@ -113,7 +110,7 @@ $multipleRows = [
];
$writer->addRows($multipleRows);
/** add a row from an arry of values */
/** Shortcut: add a row from an array of values */
$values = ['Carl', 'is', 'great!'];
$rowFromValues = WriterEntityFactory::createRowFromArray($values);
$writer->addRow($rowFromValues);
@ -121,6 +118,17 @@ $writer->addRow($rowFromValues);
$writer->close();
```
Similar to the reader, if the file extension of the file to be written is not standard, specific writers can be created this way:
```php
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Box\Spout\Common\Entity\Row;
$writer = WriterEntityFactory::createWriter(Type::XLSX);
// $writer = WriterEntityFactory::createWriter(Type::ODS);
// $writer = WriterEntityFactory::createWriter(Type::CSV);
```
For XLSX and ODS files, the number of rows per sheet is limited to *1,048,576*. By default, once this limit is reached, the writer will automatically create a new sheet and continue writing data into it.

View File

@ -4,8 +4,6 @@ title: Guides
permalink: /guides/
---
> Heads up! These Guides cover the previous version 2.x of Spout. Even though some things have changed in version 3.x - the concepts in these guides can still be beneficial. Please contribute and write new guides and recipes for Spout.
These guides focus on common and more advanced usages of {{ site.spout_html }}.<br>
If you are just starting with {{ site.spout_html }}, check out the [Getting Started page]({{ site.github.url }}/getting-started/) and the [Documentation]({{ site.github.url }}/docs/) first.

View File

@ -14,20 +14,19 @@ In order to avoid memory issues when dealing with large spreadsheets, {{ site.sp
```php
<?php
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
$existingFilePath = 'path/to/orders.xlsx';
$newFilePath = 'path/to/new-orders.xlsx';
// we need a reader to read the existing file...
$reader = ReaderFactory::create(Type::XLSX);
$reader->open($existingFilePath);
$reader = ReaderEntityFactory::createReaderFromFile($existingFilePath);
$reader->setShouldFormatDates(true); // this is to be able to copy dates
$reader->open($existingFilePath);
// ... and a writer to create the new file
$writer = WriterFactory::create(Type::XLSX);
$writer = WriterEntityFactory::createWriterFromFile($newFilePath);
$writer->openToFile($newFilePath);
// let's read the entire spreadsheet...
@ -45,7 +44,9 @@ foreach ($reader->getSheetIterator() as $sheetIndex => $sheet) {
// At this point, the new spreadsheet contains the same data as the existing one.
// So let's add the new data:
$writer->addRow(['2015-12-25', 'Christmas gift', 29, 'USD']);
$writer->addRow(
WriterEntityFactory::createRowFromArray(['2015-12-25', 'Christmas gift', 29, 'USD'])
);
$reader->close();
$writer->close();

View File

@ -27,20 +27,19 @@ We'd like to update the missing album for "Yellow Submarine", remove the Bob Mar
```php
<?php
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
$existingFilePath = '/path/to/my-music.ods';
$newFilePath = '/path/to/my-new-music.ods';
// we need a reader to read the existing file...
$reader = ReaderFactory::create(Type::ODS);
$reader = ReaderEntityFactory::createReaderFromFile($existingFilePath);
$reader->open($existingFilePath);
$reader->setShouldFormatDates(true); // this is to be able to copy dates
// ... and a writer to create the new file
$writer = WriterFactory::create(Type::ODS);
$writer = WriterEntityFactory::createWriterFromFile($newFilePath);
$writer->openToFile($newFilePath);
// let's read the entire spreadsheet
@ -51,12 +50,12 @@ foreach ($reader->getSheetIterator() as $sheetIndex => $sheet) {
}
foreach ($sheet->getRowIterator() as $rowIndex => $row) {
$songTitle = $row[0];
$artist = $row[1];
$songTitle = $row->getCellAtIndex(0);
$artist = $row->getCellAtIndex(1);
// Change the album name for "Yellow Submarine"
if ($songTitle === 'Yellow Submarine') {
$row[2] = 'The White Album';
$row->setCellAtIndex(WriterEntityFactory::createCell('The White Album'), 2);
}
// skip Bob Marley's songs
@ -69,7 +68,9 @@ foreach ($reader->getSheetIterator() as $sheetIndex => $sheet) {
// insert new song at the right position, between the 3rd and 4th rows
if ($rowIndex === 3) {
$writer->addRow(['Hotel California', 'The Eagles', 'Hotel California', 1976]);
$writer->addRow(
WriterEntityFactory::createRowFromArray(['Hotel California', 'The Eagles', 'Hotel California', 1976])
);
}
}
}

View File

@ -5,12 +5,17 @@ category: guide
permalink: /guides/read-data-from-specific-sheet/
---
Even though a spreadsheet contains multiple sheets, you may be interested in reading only one of them and skip the other ones. Here is how you can do it with Spout:
Even though a spreadsheet contains multiple sheets, you may be interested in reading only one of them and skip the other ones. Here is how you can do it with {{ site.spout_html }}:
* If you know the name of the sheet
```php?start_inline=1
$reader = ReaderFactory::create(Type:XLSX);
```php
<?php
use Box\Spout\Common\Type;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
$reader = ReaderEntityFactory::createReader(Type::XLSX);
$reader->open($filePath);
foreach ($reader->getSheetIterator() as $sheet) {
@ -28,8 +33,13 @@ $reader->close();
* If you know the position of the sheet
```php?start_inline=1
$reader = ReaderFactory::create(Type:XLSX);
```php
<?php
use Box\Spout\Common\Type;
use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;
$reader = ReaderEntityFactory::createReader(Type::XLSX);
$reader->open($filePath);
foreach ($reader->getSheetIterator() as $sheet) {

View File

@ -27,7 +27,7 @@ class MyRegularController extends Controller
// before it can be sent to the browser.
$content = '';
$reader = ReaderFactory::create(Type::XLSX);
$reader = ReaderEntityFactory::createReaderFromFile($filePath);
$reader->open($filePath);
foreach ($reader->getSheetIterator() as $sheet) {
@ -36,7 +36,7 @@ class MyRegularController extends Controller
$content .= '<tr>';
$content .= implode(array_map(function($cell) {
return '<td>' . $cell . '</td>';
}, $row));
}, $row->getCells()));
$content .= '</tr>';
}
$content .= '</table><br>';
@ -77,7 +77,7 @@ class MyStreamController extends Controller
// a callback function to retrieve data chunks.
$response->setCallback(function() use ($filePath) {
// Same code goes inside the callback.
$reader = ReaderFactory::create(Type::XLSX);
$reader = ReaderEntityFactory::createReader(Type::XLSX);
$reader->open($filePath);
$i = 0;
@ -89,7 +89,7 @@ class MyStreamController extends Controller
echo '<tr>';
echo implode(array_map(function($cell) {
return '<td>' . $cell . '</td>';
}, $row));
}, $row->getCells()));
echo '</tr>';
$i++;

Binary file not shown.

After

Width:  |  Height:  |  Size: 555 B

View File

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
viewBox="0 -256 1850 1850"
id="svg3025"
version="1.1"
inkscape:version="0.48.3.1 r9886"
width="100%"
height="100%"
sodipodi:docname="external_link_font_awesome.svg">
<metadata
id="metadata3035">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs3033" />
<sodipodi:namedview
pagecolor="#ffffff"
bordercolor="#666666"
borderopacity="1"
objecttolerance="10"
gridtolerance="10"
guidetolerance="10"
inkscape:pageopacity="0"
inkscape:pageshadow="2"
inkscape:window-width="640"
inkscape:window-height="480"
id="namedview3031"
showgrid="false"
inkscape:zoom="0.13169643"
inkscape:cx="896"
inkscape:cy="896"
inkscape:window-x="0"
inkscape:window-y="25"
inkscape:window-maximized="0"
inkscape:current-layer="svg3025" />
<g
transform="matrix(1,0,0,-1,30.372881,1426.9492)"
id="g3027">
<path
d="M 1408,608 V 288 Q 1408,169 1323.5,84.5 1239,0 1120,0 H 288 Q 169,0 84.5,84.5 0,169 0,288 v 832 Q 0,1239 84.5,1323.5 169,1408 288,1408 h 704 q 14,0 23,-9 9,-9 9,-23 v -64 q 0,-14 -9,-23 -9,-9 -23,-9 H 288 q -66,0 -113,-47 -47,-47 -47,-113 V 288 q 0,-66 47,-113 47,-47 113,-47 h 832 q 66,0 113,47 47,47 47,113 v 320 q 0,14 9,23 9,9 23,9 h 64 q 14,0 23,-9 9,-9 9,-23 z m 384,864 V 960 q 0,-26 -19,-45 -19,-19 -45,-19 -26,0 -45,19 L 1507,1091 855,439 q -10,-10 -23,-10 -13,0 -23,10 L 695,553 q -10,10 -10,23 0,13 10,23 l 652,652 -176,176 q -19,19 -19,45 0,26 19,45 19,19 45,19 h 512 q 26,0 45,-19 19,-19 19,-45 z"
id="path3029"
inkscape:connector-curvature="0"
style="fill:currentColor" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.2 KiB