Skip to content

TextGrid Improvements #4418

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org).

- Add ability to add custom functions to Calculation. [PR #4390](https://github.com/PHPOffice/PhpSpreadsheet/pull/4390)
- Add FormulaRange to IgnoredErrors. [PR #4393](https://github.com/PHPOffice/PhpSpreadsheet/pull/4393)
- TextGrid improvements. [PR #4418](https://github.com/PHPOffice/PhpSpreadsheet/pull/4418)
- Permit read to class which extends Spreadsheet. [Discussion #4402](https://github.com/PHPOffice/PhpSpreadsheet/discussions/4402) [PR #4404](https://github.com/PHPOffice/PhpSpreadsheet/pull/4404)

### Removed
Expand Down
44 changes: 41 additions & 3 deletions docs/topics/reading-and-writing-to-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -1169,6 +1169,44 @@ 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.

```php
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile("myExampleFile.xlsx");
$reader->load("spreadsheetWithCharts.xlsx", $reader::READ_DATA_ONLY | $reader::IGNORE_EMPTY_CELLS);
```
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile('myExampleFile.xlsx');
$reader->load(
'spreadsheetWithCharts.xlsx',
$reader::READ_DATA_ONLY | $reader::IGNORE_EMPTY_CELLS
);
```

## Writing Data as a Plaintext Grid

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:
```php
$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` or `strlen` methods)
- Fullwidth characters
- right-to-left characters (better display in a browser than a terminal on a non-RTL system)
- multi-line strings
73 changes: 55 additions & 18 deletions src/PhpSpreadsheet/Helper/TextGrid.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace PhpOffice\PhpSpreadsheet\Helper;

use PhpOffice\PhpSpreadsheet\Shared\StringHelper;

class TextGrid
{
private bool $isCli;
Expand All @@ -14,7 +16,13 @@ class TextGrid

private string $gridDisplay;

public function __construct(array $matrix, bool $isCli = true)
private bool $rowDividers = false;

private bool $rowHeaders = true;

private bool $columnHeaders = true;

public function __construct(array $matrix, bool $isCli = true, bool $rowDividers = false, bool $rowHeaders = true, bool $columnHeaders = true)
{
$this->rows = array_keys($matrix);
$this->columns = array_keys($matrix[$this->rows[0]]);
Expand All @@ -29,20 +37,25 @@ function (&$row): void {

$this->matrix = $matrix;
$this->isCli = $isCli;
$this->rowDividers = $rowDividers;
$this->rowHeaders = $rowHeaders;
$this->columnHeaders = $columnHeaders;
}

public function render(): string
{
$this->gridDisplay = $this->isCli ? '' : '<pre>';
$this->gridDisplay = $this->isCli ? '' : ('<pre>' . PHP_EOL);

if (!empty($this->rows)) {
$maxRow = max($this->rows);
$maxRowLength = mb_strlen((string) $maxRow) + 1;
$maxRowLength = strlen((string) $maxRow) + 1;
$columnWidths = $this->getColumnWidths();

$this->renderColumnHeader($maxRowLength, $columnWidths);
$this->renderRows($maxRowLength, $columnWidths);
$this->renderFooter($maxRowLength, $columnWidths);
if (!$this->rowDividers) {
$this->renderFooter($maxRowLength, $columnWidths);
}
}

$this->gridDisplay .= $this->isCli ? '' : '</pre>';
Expand All @@ -53,30 +66,48 @@ public function render(): string
private function renderRows(int $maxRowLength, array $columnWidths): void
{
foreach ($this->matrix as $row => $rowData) {
$this->gridDisplay .= '|' . str_pad((string) $this->rows[$row], $maxRowLength, ' ', STR_PAD_LEFT) . ' ';
if ($this->rowHeaders) {
$this->gridDisplay .= '|' . str_pad((string) $this->rows[$row], $maxRowLength, ' ', STR_PAD_LEFT) . ' ';
}
$this->renderCells($rowData, $columnWidths);
$this->gridDisplay .= '|' . PHP_EOL;
if ($this->rowDividers) {
$this->renderFooter($maxRowLength, $columnWidths);
}
}
}

private function renderCells(array $rowData, array $columnWidths): void
{
foreach ($rowData as $column => $cell) {
$displayCell = ($this->isCli) ? (string) $cell : htmlentities((string) $cell);
$valueForLength = $this->getString($cell);
$displayCell = $this->isCli ? $valueForLength : htmlentities($valueForLength);
$this->gridDisplay .= '| ';
$this->gridDisplay .= $displayCell . str_repeat(' ', $columnWidths[$column] - mb_strlen($cell ?? '') + 1);
$this->gridDisplay .= $displayCell . str_repeat(' ', $columnWidths[$column] - $this->strlen($valueForLength) + 1);
}
}

private function renderColumnHeader(int $maxRowLength, array $columnWidths): void
private function renderColumnHeader(int $maxRowLength, array &$columnWidths): void
{
$this->gridDisplay .= str_repeat(' ', $maxRowLength + 2);
if (!$this->columnHeaders) {
$this->renderFooter($maxRowLength, $columnWidths);

return;
}
foreach ($this->columns as $column => $reference) {
$columnWidths[$column] = max($columnWidths[$column], $this->strlen($reference));
}
if ($this->rowHeaders) {
$this->gridDisplay .= str_repeat(' ', $maxRowLength + 2);
}
foreach ($this->columns as $column => $reference) {
$this->gridDisplay .= '+-' . str_repeat('-', $columnWidths[$column] + 1);
}
$this->gridDisplay .= '+' . PHP_EOL;

$this->gridDisplay .= str_repeat(' ', $maxRowLength + 2);
if ($this->rowHeaders) {
$this->gridDisplay .= str_repeat(' ', $maxRowLength + 2);
}
foreach ($this->columns as $column => $reference) {
$this->gridDisplay .= '| ' . str_pad((string) $reference, $columnWidths[$column] + 1, ' ');
}
Expand All @@ -87,7 +118,9 @@ private function renderColumnHeader(int $maxRowLength, array $columnWidths): voi

private function renderFooter(int $maxRowLength, array $columnWidths): void
{
$this->gridDisplay .= '+' . str_repeat('-', $maxRowLength + 1);
if ($this->rowHeaders) {
$this->gridDisplay .= '+' . str_repeat('-', $maxRowLength + 1);
}
foreach ($this->columns as $column => $reference) {
$this->gridDisplay .= '+-';
$this->gridDisplay .= str_pad((string) '', $columnWidths[$column] + 1, '-');
Expand All @@ -112,15 +145,19 @@ private function getColumnWidth(array $columnData): int
$columnData = array_values($columnData);

foreach ($columnData as $columnValue) {
if (is_string($columnValue)) {
$columnWidth = max($columnWidth, mb_strlen($columnValue));
} elseif (is_bool($columnValue)) {
$columnWidth = max($columnWidth, mb_strlen($columnValue ? 'TRUE' : 'FALSE'));
}

$columnWidth = max($columnWidth, mb_strlen((string) $columnWidth));
$columnWidth = max($columnWidth, $this->strlen($this->getString($columnValue)));
}

return $columnWidth;
}

protected function getString(mixed $value): string
{
return StringHelper::convertToString($value, convertBool: true);
}

protected function strlen(string $value): int
{
return mb_strlen($value);
}
}
7 changes: 6 additions & 1 deletion src/PhpSpreadsheet/Shared/StringHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace PhpOffice\PhpSpreadsheet\Shared;

use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
use PhpOffice\PhpSpreadsheet\Exception as SpreadsheetException;
use Stringable;

Expand Down Expand Up @@ -647,8 +648,12 @@ public static function strlenAllowNull(?string $string): int
return strlen("$string");
}

public static function convertToString(mixed $value, bool $throw = true, string $default = ''): string
/** @param bool $convertBool If true, convert bool to locale-aware TRUE/FALSE rather than 1/null-string */
public static function convertToString(mixed $value, bool $throw = true, string $default = '', bool $convertBool = false): string
{
if ($convertBool && is_bool($value)) {
return $value ? Calculation::getTRUE() : Calculation::getFALSE();
}
if ($value === null || is_scalar($value) || $value instanceof Stringable) {
return (string) $value;
}
Expand Down
159 changes: 159 additions & 0 deletions tests/PhpSpreadsheetTests/Helper/TextGridTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
<?php

declare(strict_types=1);

namespace PhpOffice\PhpSpreadsheetTests\Helper;

use PhpOffice\PhpSpreadsheet\Helper\TextGrid;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;

class TextGridTest extends TestCase
{
#[DataProvider('providerTextGrid')]
public function testTextGrid(
bool $cli,
bool $rowDividers,
bool $rowHeaders,
bool $columnHeaders,
array $expected
): void {
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([
[6, '=TEXT(A1,"yyyy-mm-dd hh:mm")', null, 0.572917],
['="6"', '=TEXT(A2,"yyyy-mm-dd hh:mm")', null, '1<>2'],
['xyz', '=TEXT(A3,"yyyy-mm-dd hh:mm")'],
], strictNullComparison: true);
$textGrid = new TextGrid(
$sheet->toArray(null, true, true, true),
$cli,
rowDividers: $rowDividers,
rowHeaders: $rowHeaders,
columnHeaders: $columnHeaders
);
$result = $textGrid->render();
// Note that, for cli, string will end with PHP_EOL,
// so explode will add an extra null-string element
// to its array output.
$lines = explode(PHP_EOL, $result);
self::assertSame($expected, $lines);
$spreadsheet->disconnectWorksheets();
}

public static function providerTextGrid(): array
{
return [
'cli default values' => [
true, false, true, true,
[
' +-----+------------------+---+----------+',
' | A | B | C | D |',
'+---+-----+------------------+---+----------+',
'| 1 | 6 | 1900-01-06 00:00 | | 0.572917 |',
'| 2 | 6 | 1900-01-06 00:00 | | 1<>2 |',
'| 3 | xyz | xyz | | |',
'+---+-----+------------------+---+----------+',
'',
],
],
'html default values' => [
false, false, true, true,
[
'<pre>',
' +-----+------------------+---+----------+',
' | A | B | C | D |',
'+---+-----+------------------+---+----------+',
'| 1 | 6 | 1900-01-06 00:00 | | 0.572917 |',
'| 2 | 6 | 1900-01-06 00:00 | | 1&lt;&gt;2 |',
'| 3 | xyz | xyz | | |',
'+---+-----+------------------+---+----------+',
'</pre>',
],
],
'cli rowDividers' => [
true, true, true, true,
[
' +-----+------------------+---+----------+',
' | A | B | C | D |',
'+---+-----+------------------+---+----------+',
'| 1 | 6 | 1900-01-06 00:00 | | 0.572917 |',
'+---+-----+------------------+---+----------+',
'| 2 | 6 | 1900-01-06 00:00 | | 1<>2 |',
'+---+-----+------------------+---+----------+',
'| 3 | xyz | xyz | | |',
'+---+-----+------------------+---+----------+',
'',
],
],
'cli no columnHeaders' => [
true, false, true, false,
[
'+---+-----+------------------+--+----------+',
'| 1 | 6 | 1900-01-06 00:00 | | 0.572917 |',
'| 2 | 6 | 1900-01-06 00:00 | | 1<>2 |',
'| 3 | xyz | xyz | | |',
'+---+-----+------------------+--+----------+',
'',
],
],
'cli no row headers' => [
true, false, false, true,
[
'+-----+------------------+---+----------+',
'| A | B | C | D |',
'+-----+------------------+---+----------+',
'| 6 | 1900-01-06 00:00 | | 0.572917 |',
'| 6 | 1900-01-06 00:00 | | 1<>2 |',
'| xyz | xyz | | |',
'+-----+------------------+---+----------+',
'',
],
],
'cli row dividers, no row nor column headers' => [
true, true, false, false,
[
'+-----+------------------+--+----------+',
'| 6 | 1900-01-06 00:00 | | 0.572917 |',
'+-----+------------------+--+----------+',
'| 6 | 1900-01-06 00:00 | | 1<>2 |',
'+-----+------------------+--+----------+',
'| xyz | xyz | | |',
'+-----+------------------+--+----------+',
'',
],
],
];
}

public function testBool(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->fromArray([
[0, 1],
[true, false],
[true, true],
], strictNullComparison: true);
$textGrid = new TextGrid(
$sheet->toArray(null, true, false, true),
true,
rowDividers: false,
rowHeaders: false,
columnHeaders: false,
);
$expected = [
'+------+-------+',
'| 0 | 1 |',
'| TRUE | FALSE |',
'| TRUE | TRUE |',
'+------+-------+',
'',
];
$result = $textGrid->render();
$lines = explode(PHP_EOL, $result);
self::assertSame($expected, $lines);
$spreadsheet->disconnectWorksheets();
}
}