1
0
mirror of https://github.com/shuchkin/simplexlsxgen.git synced 2023-08-10 21:12:59 +03:00

52 Commits

Author SHA1 Message Date
868cf8edc0 1.0.21 2021-09-03 22:12:48 +06:00
7f5c584772 1.0.20 2021-07-29 12:16:10 +06:00
5b58103e3b 1.0.19 2021-07-28 22:01:02 +06:00
6d49a90fe7 1.0.18 2021-07-28 05:06:23 +06:00
c8a94d552a 1.0.17 2021-07-28 01:45:25 +06:00
c9fa7da689 1.0.16 2021-07-01 03:03:57 +06:00
0d059fdf6e 1.0.16 2021-07-01 03:01:35 +06:00
dcb5f8ad65 1.0.15 2021-06-22 00:57:29 +06:00
f970452779 1.0.14 2021-06-08 09:59:42 +06:00
6abd0286bb 1.0.14 2021-06-08 09:51:10 +06:00
8bfbe078db 1.0.13 2021-05-29 23:21:45 +06:00
6ece83f9ce 1.0.12 2021-05-19 10:21:09 +06:00
4f375a4c30 1.0.11 2021-05-14 16:52:30 +06:00
41c6e7ca51 Merge pull request #34 from marcrobledo/marcrobledo-fix-percentage
fix percentage with decimals
2021-05-14 16:37:33 +06:00
ef7b0fff02 fix percentage with decimals
make sign optional for percentage values with decimals
2021-05-14 10:55:07 +02:00
860da7f493 1.0.10 2021-05-03 03:22:26 +06:00
eeec88dbf0 1.0.10 2021-05-03 03:19:14 +06:00
1e866f82bf 1.0.10 2021-05-03 03:17:24 +06:00
17098b57ef 1.0.10 2021-05-03 03:08:41 +06:00
ab49ffadd7 example $xlsx_content = (string) $xlsx 2021-03-01 00:09:42 +06:00
99c6be2fb4 Added PHP Datetime object values in a cells 2021-02-26 21:45:38 +06:00
d1ccfc6f17 Added PHP Datetime object values in a cells 2021-02-26 21:39:13 +06:00
21db9eca96 * percent 2021-02-26 12:55:41 +06:00
8b6d0505b5 Fix local floats in XML 2021-01-25 22:43:37 +06:00
205396b998 Fix local floats in XML 2021-01-25 22:19:37 +06:00
42558401ef Multiple sheets support and class ready for extends now 2020-11-04 01:42:52 +06:00
07d3e91c28 Merge pull request #14 from Savino59/master
added multisheet support (keeping it compatible to the original version)
2020-11-03 20:14:34 +06:00
3abb47b9b4 added multisheet support (keeping it compatible to the original version) 2020-11-02 17:34:19 +01:00
0fc338d802 update images 2020-10-17 01:13:17 +06:00
a8093b9d8e Merge remote-tracking branch 'origin/master' 2020-10-04 16:08:32 +06:00
a9219575df disable type detection 2020-10-04 16:08:12 +06:00
476e083f29 Merge pull request #8 from jturbide/master
Fix invalid content
2020-08-28 00:26:29 +06:00
db598d4ee4 Update SimpleXLSXGen.php 2020-08-26 17:15:14 -04:00
a551f6485b Long Numbers format 2020-08-23 15:07:29 +06:00
aafe6abd5b fixed fast shared strings index 2020-08-22 13:54:34 +06:00
9b2c9d3e1c Fixed real numbers in 123.45 format detection, fast shared strings index 2020-08-21 21:57:02 +06:00
9824e5b25d Merge pull request #4 from fredriksundin/performance
Replace array_search to optimize large arrays
2020-08-21 21:40:15 +06:00
c3d64d13ef Fix strict compare bug 2020-08-19 23:09:33 +00:00
22cbd84f3c Add strict compare 2020-08-19 22:48:12 +00:00
291b508143 Replace array_search to optimize large arrays 2020-08-19 22:41:08 +00:00
5a4c04025a fixed time detection 2020-07-29 21:50:38 +06:00
982de475c9 Merge pull request #2 from boryn/patch-1
Extension '.xlsx' outside of gmdate()
2020-07-16 13:38:30 +06:00
e92d3a5284 Extension '.xlsx' outside of gmdate() 2020-07-15 23:16:48 +02:00
ca5da99160 debug example 2020-07-14 17:24:11 +06:00
8a38813b12 debug example 2020-07-14 17:19:58 +06:00
72b9f420d7 debug example 2020-07-14 15:24:51 +06:00
08e2ae6892 0.9.14 fixed num2name A-Z,AA-AZ 2020-05-31 08:35:35 +06:00
6a098dd7e4 0.9.13 if string more 160 chars, save as inlineStr 2020-05-20 23:36:47 +06:00
620388a3f6 0.9.12 readme fixed 2020-05-20 23:11:44 +06:00
0aad74dd81 0.9.11 removed XML unimportant attributes 2020-05-20 23:08:58 +06:00
02867ae14c 0.9.11 removed XML unimportant attributes 2020-05-20 23:08:29 +06:00
f74084cd35 0.9.11 removed XML unimportant attributes 2020-05-20 23:06:25 +06:00
7 changed files with 698 additions and 240 deletions

5
.gitignore vendored
View File

@ -1 +1,4 @@
vendor*
vendor*
/books.fw.png
/datatypes.fw.png
/styles.fw.png

122
CHANGELOG.md Normal file
View File

@ -0,0 +1,122 @@
# Changelog
## 1.0.21 (2021-09-03)
* Fixed saveAs / downloadAs / etc methods more than once
## 1.0.20 (2021-07-29)
* Fixed sheet names duplicates (Page, Page (1), Page (2)...)
## 1.0.19 (2021-07-28)
* Fixed sheet names duplicates
## 1.0.18 (2021-07-28)
* Fixed email regex
## 1.0.17 (2021-07-28)
* Fixed " and & in sheets names
## 1.0.16 (2021-07-01)
* Fixed "&" in hyperlinks
## 1.0.15 (2021-06-22)
* Fixed *mailto* hyperlinks detection
## 1.0.14 (2021-06-08)
* Added *mailto* hyperlinks support (thx Howard Martin)
```php
SimpleXLSXGen::fromArray([
['Mailto hyperlink', '<a href="mailto:sergey.shuchkin@gmail.com">Please email me</a>']
])->saveAs('test.xlsx');
```
## 1.0.13 (2021-05-29)
* Fixed hyperlinks in several sheets
* Added [Opencollective donation link](https://opencollective.com/simplexlsx)
## 1.0.12 (2021-05-19)
* Fixed hyperlink regex
## 1.0.11 (2021-05-14)
* Fixed 0.00% format, thx [marcrobledo](https://github.com/shuchkin/simplexlsxgen/pull/34), more examples in README.md
## 1.0.10 (2021-05-03)
Stable release
* Added hyperlinks and minimal formatting
## 0.9.25 (2021-02-26)
* Added PHP Datetime object values in a cells
## 0.9.24 (2021-02-26)
* Percent support
## 0.9.23 (2021-01-25)
* Fix local floats in XML
## 0.9.22 (2020-11-04)
* Added multiple sheets support, thx [Savino59](https://github.com/Savino59), class ready for extend now
## 0.9.21 (2020-10-17)
* Updated images
## 0.9.20 (2020-10-04)
* Disable type detection if string started with chr(0)
## 0.9.19 (2020-08-23)
* Numbers like SKU right aligned now
## 0.9.18 (2020-08-22)
* Fixed fast shared strings index
## 0.9.17 (2020-08-21)
* Fixed real numbers in 123.45 format detection, fast shared strings index (thx fredriksundin)
## 0.9.16 (2020-07-29)
* Fixed time detection in HH:MM:SS format
## 0.9.15 (2020-07-14)
* Escape of shared strings for special chars in cells [#1](https://github.com/shuchkin/simplexlsxgen/issues/1)
## 0.9.14 (2020-05-31)
* Fixed num2name A-Z,AA-AZ column names, thx Ertan Yusufoglu
## 0.9.13 (2020-05-21)
* If string more 160 chars, save as inlineStr
## 0.9.12 (2020-05-21)
* Readme fixed
## 0.9.11 (2020-05-21)
* Removed XML unimportant attributes
## 0.9.10 (2020-05-20)
* Initial release

View File

@ -1,12 +1,12 @@
# SimpleXLSXGen class 0.9.10 (Official)
[<img src="https://img.shields.io/endpoint.svg?url=https%3A%2F%2Fshieldsio-patreon.herokuapp.com%2Fshuchkin" />](https://www.patreon.com/shuchkin) [<img src="https://img.shields.io/github/license/shuchkin/simplexlsxgen" />](https://github.com/shuchkin/simplexlsxgen/blob/master/license.md) [<img src="https://img.shields.io/github/stars/shuchkin/simplexlsxgen" />](https://github.com/shuchkin/simplexlsxgen/stargazers) [<img src="https://img.shields.io/github/forks/shuchkin/simplexlsxgen" />](https://github.com/shuchkin/simplexlsxgen/network) [<img src="https://img.shields.io/github/issues/shuchkin/simplexlsxgen" />](https://github.com/shuchkin/simplexlsxgen/issues)
# SimpleXLSXGen
[<img src="https://img.shields.io/github/license/shuchkin/simplexlsxgen" />](https://github.com/shuchkin/simplexlsxgen/blob/master/license.md) [<img src="https://img.shields.io/github/stars/shuchkin/simplexlsxgen" />](https://github.com/shuchkin/simplexlsxgen/stargazers) [<img src="https://img.shields.io/github/forks/shuchkin/simplexlsxgen" />](https://github.com/shuchkin/simplexlsxgen/network) [<img src="https://img.shields.io/github/issues/shuchkin/simplexlsxgen" />](https://github.com/shuchkin/simplexlsxgen/issues)
Export data to Excel XLSX file. PHP XLSX generator. No external tools and libraries.<br/>
(!) XLSX reader [here](https://github.com/shuchkin/simplexlsx).
**Sergey Shuchkin** <sergey.shuchkin@gmail.com> 2020<br/>
**Sergey Shuchkin** <sergey.shuchkin@gmail.com> 2020-2021<br/>
*Hey, bro, please ★ the package for my motivation :)*
*Hey, bro, please ★ the package for my motivation :) and [donate](https://opencollective.com/simplexlsx) for more motivation!*
## Basic Usage
```php
@ -16,12 +16,9 @@ $books = [
[908606664, 'Slinky Malinki', 'Lynley Dodd', 'Mallinson Rendel', 'NZ']
];
$xlsx = SimpleXLSXGen::fromArray( $books );
$xlsx->saveAs('books.xlsx');
$xlsx->saveAs('books.xlsx'); // or downloadAs('books.xlsx') or $xlsx_content = (string) $xlsx
```
![XLSX screenshot](books.png)
```
// SimpleXLSXGen::download() or SimpleXSLSXGen::downloadAs('table.xlsx');
```
## Installation
The recommended way to install this library is [through Composer](https://getcomposer.org).
@ -39,14 +36,69 @@ or download class [here](https://github.com/shuchkin/simplexlsxgen/blob/master/s
$data = [
['Integer', 123],
['Float', 12.35],
['Procent', '12%'],
['Date','2020-05-20'],
['Percent', '12%'],
['Datetime', '2020-05-20 02:38:00'],
['String', 'See SimpleXLSXGen column autosize feature']
['Date','2020-05-20'],
['Time','02:38:00'],
['Datetime PHP', new DateTime('2021-02-06 21:07:00')],
['String', 'Long UTF-8 String in autoresized column'],
['Hyperlink', 'https://github.com/shuchkin/simplexlsxgen'],
['Hyperlink + Anchor', '<a href="https://github.com/shuchkin/simplexlsxgen">SimpleXLSXGen</a>'],
['RAW string', "\0".'2020-10-04 16:02:00']
];
SimpleXLSXGen::fromArray( $data )->saveAs('datatypes.xlsx');
```
![XLSX screenshot](datatypes.png)
## History
v0.9.10 (2020-05-20) initial relese
### Formatting
```php
$data = [
['Normal', '12345.67'],
['Bold', '<b>12345.67</b>'],
['Italic', '<i>12345.67</i>'],
['Underline', '<u>12345.67</u>'],
['Strike', '<s>12345.67</s>'],
['Bold + Italic', '<b><i>12345.67</i></b>'],
['Hyperlink', 'https://github.com/shuchkin/simplexlsxgen'],
['Italic + Hyperlink + Anchor', '<i><a href="https://github.com/shuchkin/simplexlsxgen">SimpleXLSXGen</a></i>'],
['Left', '<left>12345.67</left>'],
['Center', '<center>12345.67</center>'],
['Right', '<right>Right Text</right>'],
['Center + Bold', '<center><b>Name</b></center>']
];
SimpleXLSXGen::fromArray( $data )
->setDefaultFont( 'Courier New' )
->setDefaultFontSize( 14 )
->saveAs('styles_and_tags.xlsx');
```
![XLSX screenshot](styles.png)
### More examples
```php
// Fluid interface, output to browser for download
SimpleXLSXGen::fromArray( $books )->downloadAs('table.xlsx');
// Fluid interface, multiple sheets
SimpleXLSXGen::fromArray( $books )->addSheet( $books2 )->download();
// Alternative interface, sheet name, get xlsx content
$xlsx_cache = (string) (new SimpleXLSXGen)->addSheet( $books, 'Modern style');
// Classic interface
$xlsx = new SimpleXLSXGen();
$xlsx->addSheet( $books, 'Catalog 2021' );
$xlsx->addSheet( $books2, 'Stephen King catalog');
$xlsx->downloadAs('books_2021.xlsx');
exit();
```
## Debug
```php
ini_set('error_reporting', E_ALL );
ini_set('display_errors', 1 );
$data = [
['Debug', 123]
]
SimpleXLSXGen::fromArray( $data )->saveAs('debug.xlsx');
```

BIN
books.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 87 KiB

After

Width:  |  Height:  |  Size: 45 KiB

View File

@ -7,23 +7,46 @@
class SimpleXLSXGen {
public $rows;
public $template;
public $curSheet;
protected $defaultFont;
protected $defaultFontSize;
protected $sheets;
protected $template;
protected $F, $F_KEYS; // fonts
protected $XF, $XF_KEYS; // cellXfs
protected $SI, $SI_KEYS; // shared strings
const N_NORMAL = 0; // General
const N_INT = 1; // 0
const N_DEC = 2; // 0.00
const N_PERCENT_INT = 9; // 0%
const N_PRECENT_DEC = 10; // 0.00%
const N_DATE = 14; // mm-dd-yy
const N_TIME = 20; // h:mm
const N_DATETIME = 22; // m/d/yy h:mm
const F_NORMAL = 0;
const F_HYPERLINK = 1;
const F_BOLD = 2;
const F_ITALIC = 4;
const F_UNDERLINE = 8;
const F_STRIKE = 16;
const A_DEFAULT = 0;
const A_LEFT = 1;
const A_RIGHT = 2;
const A_CENTER = 3;
public function __construct() {
$this->rows = [];
$this->curSheet = -1;
$this->defaultFont = 'Calibri';
$this->sheets = [ ['name' => 'Sheet1', 'rows' => [], 'hyperlinks' => [] ] ];
$this->SI = []; // sharedStrings index
$this->SI_KEYS = []; // & keys
$this->F = [ self::F_NORMAL ]; // fonts
$this->F_KEYS = [0]; // & keys
$this->XF = [ [self::N_NORMAL, self::F_NORMAL, self::A_DEFAULT] ]; // styles
$this->XF_KEYS = ['N0F0A0' => 0 ]; // & keys
$this->template = [
'[Content_Types].xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Override PartName="/_rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>
<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>
<Override PartName="/xl/_rels/workbook.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>
<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>
<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
</Types>',
/* <Override PartName="/xl/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/> */
'_rels/.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
@ -44,62 +67,90 @@ class SimpleXLSXGen {
'xl/_rels/workbook.xml.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/>
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/></Relationships>',
{SHEETS}',
'xl/worksheets/sheet1.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><dimension ref="{REF}"/><cols>{COLS}</cols><sheetData>{ROWS}</sheetData></worksheet>',
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
><dimension ref="{REF}"/>{COLS}<sheetData>{ROWS}</sheetData>{HYPERLINKS}</worksheet>',
'xl/worksheets/_rels/sheet1.xml.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{HYPERLINKS}</Relationships>',
'xl/sharedStrings.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="{CNT}" uniqueCount="{CNT}">{STRINGS}</sst>',
'xl/styles.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<fonts count="1"><font><name val="Calibri"/><family val="2"/></font></fonts>
{FONTS}
<fills count="1"><fill><patternFill patternType="none"/></fill></fills>
<borders count="1"><border diagonalUp="false" diagonalDown="false"><left/><right/><top/><bottom/><diagonal/></border></borders>
<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>
<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" /></cellStyleXfs>
<cellXfs count="6">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="9" fontId="0" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="10" fontId="0" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="14" fontId="0" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="20" fontId="0" fillId="0" borderId="0" xfId="0"/>
<xf numFmtId="22" fontId="0" fillId="0" borderId="0" xfId="0"/>
</cellXfs>
<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles>
{XF}
<cellStyles count="1">
<cellStyle name="Normal" xfId="0" builtinId="0"/>
</cellStyles>
</styleSheet>',
'xl/workbook.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<fileVersion appName="'.__CLASS__.'"/>
<workbookPr backupFile="false" showObjects="all" date1904="false"/>
<bookViews>
<workbookView showHorizontalScroll="true" showVerticalScroll="true" showSheetTabs="true" xWindow="0" yWindow="0" windowWidth="16384" windowHeight="8192" tabRatio="205" firstSheet="0" activeTab="0"/>
</bookViews>
<sheets><sheet name="Sheet1" sheetId="1" state="visible" r:id="rId2"/></sheets>
<calcPr iterateCount="100" refMode="A1" iterate="false" iterateDelta="0.001"/>
</workbook>'
<fileVersion appName="'.__CLASS__.'"/><sheets>
{SHEETS}
</sheets></workbook>',
'[Content_Types].xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Override PartName="/rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>
<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>
<Override PartName="/xl/_rels/workbook.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>
<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
{TYPES}
</Types>',
];
// <col min="1" max="1" width="22.1796875" bestFit="1" customWidth="1"/>
// <row r="1" spans="1:2" x14ac:dyDescent="0.35"><c r="A1" t="s"><v>0</v></c><c r="B1"><v>100</v></c></row><row r="2" spans="1:2" x14ac:dyDescent="0.35"><c r="A2" t="s"><v>1</v></c><c r="B2"><v>200</v></c></row>
// <si><t>Простой шаблон</t></si><si><t>Будем делать генератор</t></si>
}
public static function fromArray( array $rows ) {
$xlsx = new self();
$xlsx->setRows( $rows );
return $xlsx;
public static function fromArray( array $rows, $sheetName = null ) {
$xlsx = new static();
return $xlsx->addSheet( $rows, $sheetName );
}
public function setRows( $rows ) {
if ( is_array( $rows ) && isset( $rows[0] ) && is_array($rows[0]) ) {
$this->rows = $rows;
public function addSheet( array $rows, $name = null ) {
$this->curSheet++;
if ( $name === null ) { // autogenerated sheet names
$name = 'Sheet'.($this->curSheet+1);
} else {
$this->rows = [];
$names = [];
foreach( $this->sheets as $sh ) {
$names[ strtoupper( $sh['name']) ] = 1;
}
for( $i = 0; $i < 100; $i++ ) {
$new_name = ($i === 0) ? $name : $name .' ('.$i.')';
$NEW_NAME = strtoupper( $new_name );
if ( !isset( $names[ $NEW_NAME ]) ) {
$name = $new_name;
break;
}
}
}
$this->sheets[$this->curSheet] = ['name' => $name, 'hyperlinks' => []];
if ( is_array( $rows ) && isset( $rows[0] ) && is_array($rows[0]) ) {
$this->sheets[$this->curSheet]['rows'] = $rows;
} else {
$this->sheets[$this->curSheet]['rows'] = [];
}
return $this;
}
public function __toString() {
$fh = fopen( 'php://memory', 'wb' );
if ( ! $fh ) {
return '';
}
if ( ! $this->_generate( $fh ) ) {
if ( ! $this->_write( $fh ) ) {
fclose( $fh );
return '';
}
@ -108,12 +159,13 @@ class SimpleXLSXGen {
return (string) fread( $fh, $size );
}
public function saveAs( $filename ) {
$fh = fopen( $filename, 'wb' );
if (!$fh) {
return false;
}
if ( !$this->_generate($fh) ) {
if ( !$this->_write($fh) ) {
fclose($fh);
return false;
}
@ -121,16 +173,18 @@ class SimpleXLSXGen {
return true;
}
public function download() {
return $this->downloadAs( gmdate('YmdHi.xlsx') );
return $this->downloadAs( gmdate('YmdHi') . '.xlsx' );
}
public function downloadAs( $filename ) {
$fh = fopen('php://memory','wb');
if (!$fh) {
return false;
}
if ( !$this->_generate( $fh )) {
if ( !$this->_write( $fh )) {
fclose( $fh );
return false;
}
@ -152,185 +206,119 @@ class SimpleXLSXGen {
return true;
}
private function _generate( $fh ) {
protected function _write( $fh ) {
$zipSignature = "\x50\x4b\x03\x04"; // local file header signature
$dirSignature = "\x50\x4b\x01\x02"; // central dir header signature
$dirSignatureE= "\x50\x4b\x05\x06"; // end of central dir signature
$zipComments = 'Generated by '.__CLASS__.' PHP class, thanks sergey.shuchkin@gmail.com';
// $fh = fopen( $filename, 'wb' );
if (!$fh) {
return false;
}
$SI = [];
$COLS = [];
$ROWS = [];
if ( count($this->rows) ) {
$CUR_ROW = 0;
$COL = [];
foreach( $this->rows as $r ) {
$CUR_ROW++;
$row = '<row r="'.$CUR_ROW.'">';
$CUR_COL = 0;
foreach( $r as $k => $v ) {
$CUR_COL++;
if ( !isset($COL[ $CUR_COL ])) {
$COL[ $CUR_COL ] = 0;
}
if ( $v === null || $v === '' ) {
continue;
}
$COL[ $CUR_COL ] = max( mb_strlen( (string) $v ), $COL[ $CUR_COL ] );
$cdrec = ''; // central directory content
$entries= 0; // number of zipped files
$cnt_sheets = count( $this->sheets );
$cname = $this->_num2name($CUR_COL).$CUR_ROW;
$ct = $cs = null;
if ( is_string($v) ) {
if ( preg_match( '/^[-+]?\d{1,18}$/', $v ) ) {
$cv = ltrim($v,'+');
} elseif ( preg_match('/^[-+]?\d+\.?\d*$/', $v ) ) {
$cv = ltrim($v,'+');
} elseif ( preg_match('/^([-+]?\d+)%$/', $v, $m) ) {
$cv = round( $m[1] / 100, 2);
$cs = 1; // [9] 0%
} elseif ( preg_match('/^([-+]\d+\.\d*)%$/', $v, $m) ) {
$cv = round( $m[1] / 100, 4 );
$cs = 2; // [10] 0.00%
} elseif ( preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d)$/', $v, $m ) ){
$cv = $this->_date2excel($m[1],$m[2],$m[3]);
$cs = 3; // [14] mm-dd-yy
} elseif ( preg_match('/^(\d\d):(\d\d):(\d\d)$/', $v, $m ) ){
$cv = $this->_date2excel(0,0,0,$m[1],$m[2],$m[3]);
$cs = 4; // [14] mm-dd-yy
} elseif ( preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$/', $v, $m ) ){
$cv = $this->_date2excel($m[1],$m[2],$m[3],$m[4],$m[5],$m[6]);
$cs = 5; // [22] m/d/yy h:mm
} else {
$ct = 's'; // shared string
$v = htmlentities($v, ENT_QUOTES);
$cv = array_search( $v, $SI, true );
if ( $cv === false ) {
$SI[] = $v;
$cv = count( $SI ) - 1;
}
}
} elseif ( is_int( $v ) || is_float( $v ) ) {
$cv = $v;
} else {
continue;
}
$row .= '<c r="' . $cname . '"'.($ct ? ' t="'.$ct.'"' : '').($cs ? ' s="'.$cs.'"' : '').'><v>' . $cv . "</v></c>\r\n";
foreach ($this->template as $cfilename => $template ) {
if ( $cfilename === 'xl/_rels/workbook.xml.rels' ) {
$s = '';
for ( $i = 0; $i < $cnt_sheets; $i++) {
$s .= '<Relationship Id="rId'.($i+2).'" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"'.
' Target="worksheets/sheet'.($i+1).".xml\"/>\n";
}
$ROWS[] = $row . "</row>\r\n";
$s .= '<Relationship Id="rId'.($i+2).'" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/></Relationships>';
$template = str_replace('{SHEETS}', $s, $template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
} elseif ( $cfilename === 'xl/workbook.xml' ) {
$s = '';
foreach ( $this->sheets as $k => $v ) {
$s .= '<sheet name="' . $this->esc( $v['name'] ) . '" sheetId="' . ( $k + 1) . '" state="visible" r:id="rId' . ( $k + 2) . '"/>';
}
$template = str_replace('{SHEETS}', $s, $template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
}
foreach ( $COL as $k => $max ) {
$COLS[] = '<col min="'.$k.'" max="'.$k.'" width="'.min( $max, 60).'" bestFit="1" customWidth="1" />';
}
$REF = 'A1:'.$this->_num2name(count($COLS)).$CUR_ROW;
} else {
// $COLS[] = '<col min="1" max="7" width="7.18" bestFit="1" customWidth="1" />';
$COLS[] = '<col min="1" max="7" bestFit="1" />';
$ROWS[] = '<row r="1"><c r="A1" t="s"><v>0</v></c></row>';
$REF = 'A1:A1';
$SI[] = 'No Data';
}
$SI_CNT = count($SI);
$SI = '<si><t>'.implode("</t></si>\r\n<si><t>", $SI).'</t></si>';
$cdrec = '';
foreach ($this->template as $cfilename => $data ) {
if ( $cfilename === 'docProps/core.xml' ) {
$data = str_replace('{DATE}', gmdate('Y-m-d\TH:i:s\Z'), $data);
elseif ( $cfilename === 'docProps/core.xml' ) {
$template = str_replace('{DATE}', gmdate('Y-m-d\TH:i:s\Z'), $template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
} elseif ( $cfilename === 'xl/sharedStrings.xml' ) {
$data = str_replace(['{CNT}', '{STRINGS}'], [ $SI_CNT, $SI ], $data );
if (!count($this->SI)) {
$this->SI[] = 'No Data';
}
$si_cnt = count($this->SI);
$si = '<si><t>'.implode("</t></si>\r\n<si><t>", $this->SI).'</t></si>';
$template = str_replace(['{CNT}', '{STRINGS}'], [ $si_cnt, $si ], $template );
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
} elseif ( $cfilename === 'xl/worksheets/sheet1.xml' ) {
$data = str_replace(['{REF}','{COLS}','{ROWS}'],[ $REF, implode("\r\n", $COLS), implode("\r\n",$ROWS) ], $data );
foreach ( $this->sheets as $k => $v ) {
$filename = 'xl/worksheets/sheet'.($k+1).'.xml';
$xml = $this->_sheetToXML($k, $template);
$this->_writeEntry($fh, $cdrec, $filename, $xml );
$entries++;
}
$xml = null;
} elseif ( $cfilename === 'xl/worksheets/_rels/sheet1.xml.rels' ) {
foreach ( $this->sheets as $k => $v ) {
if ( count($v['hyperlinks'])) {
$RH = [];
$filename = 'xl/worksheets/_rels/sheet' . ( $k + 1 ) . '.xml.rels';
foreach ( $v['hyperlinks'] as $h ) {
$RH[] = '<Relationship Id="' . $h['ID'] . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="' . $this->esc($h['H']) . '" TargetMode="External"/>';
}
$xml = str_replace( '{HYPERLINKS}', implode( "\r\n", $RH ), $template );
$this->_writeEntry( $fh, $cdrec, $filename, $xml );
$entries++;
}
}
$xml = null;
} elseif ( $cfilename === '[Content_Types].xml' ) {
$TYPES = ['<Override PartName="/_rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'];
foreach ( $this->sheets as $k => $v) {
$TYPES[] = '<Override PartName="/xl/worksheets/sheet'.($k+1).
'.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
if (count( $v['hyperlinks'])) {
$TYPES[] = '<Override PartName="/xl/worksheets/_rels/sheet'.($k+1).'.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
}
}
$template = str_replace('{TYPES}', implode("\r\n", $TYPES), $template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
} elseif ( $cfilename === 'xl/styles.xml' ) {
$FONTS = ['<fonts count="'.count($this->F).'">'];
foreach ( $this->F as $f ) {
$FONTS[] = '<font><name val="'.$this->defaultFont.'"/><family val="2"/>'
. ( $this->defaultFontSize ? '<sz val="'.$this->defaultFontSize.'"/>' : '' )
.( $f & self::F_BOLD ? '<b/>' : '')
.( $f & self::F_ITALIC ? '<i/>' : '')
.( $f & self::F_UNDERLINE ? '<u/>' : '')
.( $f & self::F_STRIKE ? '<strike/>' : '')
.( $f & self::F_HYPERLINK ? '<color rgb="FF0563C1"/><u/>' : '')
.'</font>';
}
$FONTS[] = '</fonts>';
$XF = ['<cellXfs count="'.count($this->XF).'">'];
foreach( $this->XF as $xf ) {
$align = ($xf[2] === self::A_LEFT ? ' applyAlignment="1"><alignment horizontal="left"/>' : '')
.($xf[2] === self::A_RIGHT ? ' applyAlignment="1"><alignment horizontal="right"/>' : '')
.($xf[2] === self::A_CENTER ? ' applyAlignment="1"><alignment horizontal="center"/>' : '');
$XF[] = '<xf numFmtId="'.$xf[0].'" fontId="'.$xf[1].'" fillId="0" borderId="0" xfId="0"'
.($xf[0] > 0 ? ' applyNumberFormat="1"' : '')
.($align ? $align . '</xf>' : '/>');
}
$XF[] = '</cellXfs>';
$template = str_replace(['{FONTS}','{XF}'], [implode("\r\n", $FONTS), implode("\r\n", $XF)], $template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
} else {
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
}
$e = [];
$e['uncsize'] = mb_strlen($data, '8bit');
// if data to compress is too small, just store it
if($e['uncsize'] < 256){
$e['comsize'] = $e['uncsize'];
$e['vneeded'] = 10;
$e['cmethod'] = 0;
$zdata = $data;
} else{ // otherwise, compress it
$zdata = gzcompress($data);
$zdata = substr(substr($zdata, 0, - 4 ), 2); // fix crc bug (thanks to Eric Mueller)
$e['comsize'] = mb_strlen($zdata, '8bit');
$e['vneeded'] = 10;
$e['cmethod'] = 8;
}
$e['bitflag'] = 0;
$e['crc_32'] = crc32($data);
// Convert date and time to DOS Format, and set then
$lastmod_timeS = str_pad(decbin(date('s')>=32?date('s')-32:date('s')), 5, '0', STR_PAD_LEFT);
$lastmod_timeM = str_pad(decbin(date('i')), 6, '0', STR_PAD_LEFT);
$lastmod_timeH = str_pad(decbin(date('H')), 5, '0', STR_PAD_LEFT);
$lastmod_dateD = str_pad(decbin(date('d')), 5, '0', STR_PAD_LEFT);
$lastmod_dateM = str_pad(decbin(date('m')), 4, '0', STR_PAD_LEFT);
$lastmod_dateY = str_pad(decbin(date('Y')-1980), 7, '0', STR_PAD_LEFT);
# echo "ModTime: $lastmod_timeS-$lastmod_timeM-$lastmod_timeH (".date("s H H").")\n";
# echo "ModDate: $lastmod_dateD-$lastmod_dateM-$lastmod_dateY (".date("d m Y").")\n";
$e['modtime'] = bindec("$lastmod_timeH$lastmod_timeM$lastmod_timeS");
$e['moddate'] = bindec("$lastmod_dateY$lastmod_dateM$lastmod_dateD");
$e['offset'] = ftell($fh);
/** @noinspection DisconnectedForeachInstructionInspection */
fwrite($fh, $zipSignature);
fwrite($fh, pack('s', $e['vneeded'])); // version_needed
fwrite($fh, pack('s', $e['bitflag'])); // general_bit_flag
fwrite($fh, pack('s', $e['cmethod'])); // compression_method
fwrite($fh, pack('s', $e['modtime'])); // lastmod_time
fwrite($fh, pack('s', $e['moddate'])); // lastmod_date
fwrite($fh, pack('V', $e['crc_32'])); // crc-32
fwrite($fh, pack('I', $e['comsize'])); // compressed_size
fwrite($fh, pack('I', $e['uncsize'])); // uncompressed_size
fwrite($fh, pack('s', mb_strlen($cfilename, '8bit'))); // file_name_length
/** @noinspection DisconnectedForeachInstructionInspection */
fwrite($fh, pack('s', 0)); // extra_field_length
fwrite($fh, $cfilename); // file_name
// ignoring extra_field
fwrite($fh, $zdata);
// Append it to central dir
$e['external_attributes'] = (substr($cfilename, -1) === '/'&&!$zdata)?16:32; // Directory or file name
$e['comments'] = '';
$cdrec .= $dirSignature;
$cdrec .= "\x0\x0"; // version made by
$cdrec .= pack('v', $e['vneeded']); // version needed to extract
$cdrec .= "\x0\x0"; // general bit flag
$cdrec .= pack('v', $e['cmethod']); // compression method
$cdrec .= pack('v', $e['modtime']); // lastmod time
$cdrec .= pack('v', $e['moddate']); // lastmod date
$cdrec .= pack('V', $e['crc_32']); // crc32
$cdrec .= pack('V', $e['comsize']); // compressed filesize
$cdrec .= pack('V', $e['uncsize']); // uncompressed filesize
$cdrec .= pack('v', mb_strlen($cfilename,'8bit')); // file name length
$cdrec .= pack('v', 0); // extra field length
$cdrec .= pack('v', mb_strlen($e['comments'],'8bit')); // file comment length
$cdrec .= pack('v', 0); // disk number start
$cdrec .= pack('v', 0); // internal file attributes
$cdrec .= pack('V', $e['external_attributes']); // internal file attributes
$cdrec .= pack('V', $e['offset']); // relative offset of local header
$cdrec .= $cfilename;
$cdrec .= $e['comments'];
}
$before_cd = ftell($fh);
fwrite($fh, $cdrec);
@ -339,8 +327,8 @@ class SimpleXLSXGen {
fwrite($fh, $dirSignatureE);
fwrite($fh, pack('v', 0)); // number of this disk
fwrite($fh, pack('v', 0)); // number of the disk with the start of the central directory
fwrite($fh, pack('v', count( $this->template ))); // total # of entries "on this disk"
fwrite($fh, pack('v', count( $this->template ))); // total # of entries overall
fwrite($fh, pack('v', $entries)); // total # of entries "on this disk"
fwrite($fh, pack('v', $entries)); // total # of entries overall
fwrite($fh, pack('V', mb_strlen($cdrec,'8bit'))); // size of central dir
fwrite($fh, pack('V', $before_cd)); // offset to start of central dir
fwrite($fh, pack('v', mb_strlen($zipComments,'8bit'))); // .zip file comment length
@ -348,17 +336,301 @@ class SimpleXLSXGen {
return true;
}
private function _num2name($num) {
$numeric = ($num-1) % 26;
protected function _writeEntry($fh, &$cdrec, $cfilename, $data) {
$zipSignature = "\x50\x4b\x03\x04"; // local file header signature
$dirSignature = "\x50\x4b\x01\x02"; // central dir header signature
$e = [];
$e['uncsize'] = mb_strlen($data, '8bit');
// if data to compress is too small, just store it
if($e['uncsize'] < 256){
$e['comsize'] = $e['uncsize'];
$e['vneeded'] = 10;
$e['cmethod'] = 0;
$zdata = $data;
} else{ // otherwise, compress it
$zdata = gzcompress($data);
$zdata = substr(substr($zdata, 0, - 4 ), 2); // fix crc bug (thanks to Eric Mueller)
$e['comsize'] = mb_strlen($zdata, '8bit');
$e['vneeded'] = 10;
$e['cmethod'] = 8;
}
$e['bitflag'] = 0;
$e['crc_32'] = crc32($data);
// Convert date and time to DOS Format, and set then
$lastmod_timeS = str_pad(decbin(date('s')>=32?date('s')-32:date('s')), 5, '0', STR_PAD_LEFT);
$lastmod_timeM = str_pad(decbin(date('i')), 6, '0', STR_PAD_LEFT);
$lastmod_timeH = str_pad(decbin(date('H')), 5, '0', STR_PAD_LEFT);
$lastmod_dateD = str_pad(decbin(date('d')), 5, '0', STR_PAD_LEFT);
$lastmod_dateM = str_pad(decbin(date('m')), 4, '0', STR_PAD_LEFT);
$lastmod_dateY = str_pad(decbin(date('Y')-1980), 7, '0', STR_PAD_LEFT);
# echo "ModTime: $lastmod_timeS-$lastmod_timeM-$lastmod_timeH (".date("s H H").")\n";
# echo "ModDate: $lastmod_dateD-$lastmod_dateM-$lastmod_dateY (".date("d m Y").")\n";
$e['modtime'] = bindec("$lastmod_timeH$lastmod_timeM$lastmod_timeS");
$e['moddate'] = bindec("$lastmod_dateY$lastmod_dateM$lastmod_dateD");
$e['offset'] = ftell($fh);
fwrite($fh, $zipSignature);
fwrite($fh, pack('s', $e['vneeded'])); // version_needed
fwrite($fh, pack('s', $e['bitflag'])); // general_bit_flag
fwrite($fh, pack('s', $e['cmethod'])); // compression_method
fwrite($fh, pack('s', $e['modtime'])); // lastmod_time
fwrite($fh, pack('s', $e['moddate'])); // lastmod_date
fwrite($fh, pack('V', $e['crc_32'])); // crc-32
fwrite($fh, pack('I', $e['comsize'])); // compressed_size
fwrite($fh, pack('I', $e['uncsize'])); // uncompressed_size
fwrite($fh, pack('s', mb_strlen($cfilename, '8bit'))); // file_name_length
fwrite($fh, pack('s', 0)); // extra_field_length
fwrite($fh, $cfilename); // file_name
// ignoring extra_field
fwrite($fh, $zdata);
// Append it to central dir
$e['external_attributes'] = (substr($cfilename, -1) === '/'&&!$zdata)?16:32; // Directory or file name
$e['comments'] = '';
$cdrec .= $dirSignature;
$cdrec .= "\x0\x0"; // version made by
$cdrec .= pack('v', $e['vneeded']); // version needed to extract
$cdrec .= "\x0\x0"; // general bit flag
$cdrec .= pack('v', $e['cmethod']); // compression method
$cdrec .= pack('v', $e['modtime']); // lastmod time
$cdrec .= pack('v', $e['moddate']); // lastmod date
$cdrec .= pack('V', $e['crc_32']); // crc32
$cdrec .= pack('V', $e['comsize']); // compressed filesize
$cdrec .= pack('V', $e['uncsize']); // uncompressed filesize
$cdrec .= pack('v', mb_strlen($cfilename,'8bit')); // file name length
$cdrec .= pack('v', 0); // extra field length
$cdrec .= pack('v', mb_strlen($e['comments'],'8bit')); // file comment length
$cdrec .= pack('v', 0); // disk number start
$cdrec .= pack('v', 0); // internal file attributes
$cdrec .= pack('V', $e['external_attributes']); // internal file attributes
$cdrec .= pack('V', $e['offset']); // relative offset of local header
$cdrec .= $cfilename;
$cdrec .= $e['comments'];
}
protected function _sheetToXML($idx, $template) {
// locale floats fr_FR 1.234,56 -> 1234.56
$_loc = setlocale(LC_NUMERIC, 0);
setlocale(LC_NUMERIC,'C');
$COLS = [];
$ROWS = [];
if ( count($this->sheets[$idx]['rows']) ) {
$COLS[] = '<cols>';
$CUR_ROW = 0;
$COL = [];
foreach( $this->sheets[$idx]['rows'] as $r ) {
$CUR_ROW++;
$row = '<row r="'.$CUR_ROW.'">';
$CUR_COL = 0;
foreach( $r as $v ) {
$CUR_COL++;
if ( !isset($COL[ $CUR_COL ])) {
$COL[ $CUR_COL ] = 0;
}
if ( $v === null || $v === '' ) {
continue;
}
$cname = $this->num2name($CUR_COL) . $CUR_ROW;
$ct = $cv = null;
$N = $F = $A = 0;
if ( is_string($v) ) {
if ( $v[0] === "\0" ) { // RAW value as string
$v = substr($v,1);
$vl = mb_strlen( $v );
} else {
if ( strpos( $v, '<' ) !== false ) { // tags?
if ( strpos( $v, '<b>' ) !== false ) {
$F += self::F_BOLD;
}
if ( strpos( $v, '<i>' ) !== false ) {
$F += self::F_ITALIC;
}
if ( strpos( $v, '<u>' ) !== false ) {
$F += self::F_UNDERLINE;
}
if ( strpos( $v, '<s>' ) !== false ) {
$F += self::F_STRIKE;
}
if ( strpos( $v, '<left>' ) !== false ) {
$A += self::A_LEFT;
}
if ( strpos( $v, '<center>' ) !== false ) {
$A += self::A_CENTER;
}
if ( strpos( $v, '<right>' ) !== false ) {
$A += self::A_RIGHT;
}
if ( preg_match( '/<a href="(https?:\/\/[^"]+)">(.*?)<\/a>/i', $v, $m ) ) {
$h = explode( '#', $m[1] );
$this->sheets[ $idx ]['hyperlinks'][] = ['ID' => 'rId' . ( count( $this->sheets[ $idx ]['hyperlinks'] ) + 1 ), 'R' => $cname, 'H' => $h[0], 'L' => isset( $h[1] ) ? $h[1] : ''];
$F = self::F_HYPERLINK; // Hyperlink
}
if ( preg_match( '/<a href="(mailto?:[^"]+)">(.*?)<\/a>/i', $v, $m ) ) {
$this->sheets[ $idx ]['hyperlinks'][] = ['ID' => 'rId' . ( count( $this->sheets[ $idx ]['hyperlinks'] ) + 1 ), 'R' => $cname, 'H' => $m[1], 'L' => ''];
$F = self::F_HYPERLINK; // mailto hyperlink
}
$v = strip_tags( $v );
} // tags
$vl = mb_strlen( $v );
if ( $v === '0' || preg_match( '/^[-+]?[1-9]\d{0,14}$/', $v ) ) { // Integer as General
$cv = ltrim( $v, '+' );
if ( $vl > 10 ) {
$N = self::N_INT; // [1] 0
}
} elseif ( preg_match( '/^[-+]?(0|[1-9]\d*)\.(\d+)$/', $v, $m ) ) {
$cv = ltrim( $v, '+' );
if ( strlen( $m[2] ) < 3 ) {
$N = self::N_DEC;
}
} elseif ( preg_match( '/^([-+]?\d+)%$/', $v, $m ) ) {
$cv = round( $m[1] / 100, 2 );
$N = self::N_PERCENT_INT; // [9] 0%
} elseif ( preg_match( '/^([-+]?\d+\.\d+)%$/', $v, $m ) ) {
$cv = round( $m[1] / 100, 4 );
$N = self::N_PRECENT_DEC; // [10] 0.00%
} elseif ( preg_match( '/^(\d\d\d\d)-(\d\d)-(\d\d)$/', $v, $m ) ) {
$cv = $this->date2excel( $m[1], $m[2], $m[3] );
$N = self::N_DATE; // [14] mm-dd-yy
} elseif ( preg_match( '/^(\d\d)\/(\d\d)\/(\d\d\d\d)$/', $v, $m ) ) {
$cv = $this->date2excel( $m[3], $m[2], $m[1] );
$N = self::N_DATE; // [14] mm-dd-yy
} elseif ( preg_match( '/^(\d\d):(\d\d):(\d\d)$/', $v, $m ) ) {
$cv = $this->date2excel( 0, 0, 0, $m[1], $m[2], $m[3] );
$N = self::N_TIME; // time
} elseif ( preg_match( '/^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$/', $v, $m ) ) {
$cv = $this->date2excel( $m[1], $m[2], $m[3], $m[4], $m[5], $m[6] );
$N = self::N_DATETIME; // [22] m/d/yy h:mm
} elseif ( preg_match( '/^(\d\d)\/(\d\d)\/(\d\d\d\d) (\d\d):(\d\d):(\d\d)$/', $v, $m ) ) {
$cv = $this->date2excel( $m[3], $m[2], $m[1], $m[4], $m[5], $m[6] );
$N = self::N_DATETIME; // [22] m/d/yy h:mm
} elseif ( preg_match( '/^[0-9+-.]+$/', $v ) ) { // Long ?
$A = self::A_RIGHT;
} elseif ( preg_match( '/^https?:\/\/\S+$/i', $v ) ) {
$h = explode( '#', $v );
$this->sheets[ $idx ]['hyperlinks'][] = ['ID' => 'rId' . ( count( $this->sheets[ $idx ]['hyperlinks'] ) + 1 ), 'R' => $cname, 'H' => $h[0], 'L' => isset( $h[1] ) ? $h[1] : ''];
$F = self::F_HYPERLINK; // Hyperlink
} elseif ( preg_match( "/^[a-zA-Z0-9_\.\-]+@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/", $v ) ) {
$this->sheets[ $idx ]['hyperlinks'][] = ['ID' => 'rId' . ( count( $this->sheets[ $idx ]['hyperlinks'] ) + 1 ), 'R' => $cname, 'H' => 'mailto:' . $v, 'L' => ''];
$F = self::F_HYPERLINK; // Hyperlink
}
}
if ( !$cv) {
$v = $this->esc( $v );
if ( mb_strlen( $v ) > 160 ) {
$ct = 'inlineStr';
$cv = $v;
} else {
$ct = 's'; // shared string
$cv = false;
$skey = '~' . $v;
if ( isset( $this->SI_KEYS[ $skey ] ) ) {
$cv = $this->SI_KEYS[ $skey ];
}
if ( $cv === false ) {
$this->SI[] = $v;
$cv = count( $this->SI ) - 1;
$this->SI_KEYS[ $skey ] = $cv;
}
}
}
} elseif ( is_int( $v ) ) {
$vl = mb_strlen( (string) $v );
$cv = $v;
} elseif ( is_float( $v ) ) {
$vl = mb_strlen( (string) $v );
$cv = $v;
} elseif ( $v instanceof DateTime ) {
$vl = 16;
$cv = $this->date2excel( $v->format('Y'), $v->format('m'), $v->format('d'), $v->format('H'), $v->format('i'), $v->format('s') );
$N = self::N_DATETIME; // [22] m/d/yy h:mm
} else {
continue;
}
$COL[ $CUR_COL ] = max( $vl, $COL[ $CUR_COL ] );
$cs = 0;
if ( $N + $F + $A > 0 ) {
if ( isset($this->F_KEYS[ $F ] ) ) {
$cf = $this->F_KEYS[ $F ];
} else {
$cf = count($this->F);
$this->F_KEYS[$F] = $cf;
$this->F[] = $F;
}
$NFA = 'N' . $N . 'F' . $cf . 'A' . $A;
if ( isset( $this->XF_KEYS[ $NFA ] ) ) {
$cs = $this->XF_KEYS[ $NFA ];
}
if ( $cs === 0 ) {
$cs = count( $this->XF );
$this->XF_KEYS[ $NFA ] = $cs;
$this->XF[] = [$N, $cf, $A];
}
}
$row .= '<c r="' . $cname . '"'.($ct ? ' t="'.$ct.'"' : '').($cs ? ' s="'.$cs.'"' : '').'>'
.($ct === 'inlineStr' ? '<is><t>'.$cv.'</t></is>' : '<v>' . $cv . '</v>')."</c>\r\n";
}
$ROWS[] = $row . "</row>\r\n";
}
foreach ( $COL as $k => $max ) {
$COLS[] = '<col min="'.$k.'" max="'.$k.'" width="'.min( $max+1, 60).'" />';
}
$COLS[] = '</cols>';
$REF = 'A1:'.$this->num2name(count($COLS)) . $CUR_ROW;
} else {
$ROWS[] = '<row r="1"><c r="A1" t="s"><v>0</v></c></row>';
$REF = 'A1:A1';
}
$HYPERLINKS = [];
if ( count( $this->sheets[$idx]['hyperlinks']) ) {
$HYPERLINKS[] = '<hyperlinks>';
foreach ( $this->sheets[$idx]['hyperlinks'] as $h ) {
$HYPERLINKS[] = '<hyperlink ref="' . $h['R'] . '" r:id="' . $h['ID'] . '" location="' . $this->esc( $h['L'] ) . '" display="' . $this->esc( $h['H'] . ( $h['L'] ? ' - ' . $h['L'] : '' ) ) . '" />';
}
$HYPERLINKS[] = '</hyperlinks>';
}
//restore locale
setlocale(LC_NUMERIC, $_loc);
return str_replace(['{REF}','{COLS}','{ROWS}','{HYPERLINKS}'],
[ $REF, implode("\r\n", $COLS), implode("\r\n",$ROWS), implode("\r\n", $HYPERLINKS) ],
$template );
}
public function num2name($num) {
$numeric = ($num - 1) % 26;
$letter = chr( 65 + $numeric );
$num2 = (int) ( ($num-1) / 26 );
if ( $num2 > 0 ) {
return $this->_num2name( $num2 - 1 ) . $letter;
return $this->num2name( $num2 ) . $letter;
}
return $letter;
}
private function _date2excel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) {
public function date2excel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) {
$excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
if ( $year === 0 ) {
return $excelTime;
}
// self::CALENDAR_WINDOWS_1900
$excel1900isLeapYear = True;
if (((int)$year === 1900) && ($month <= 2)) { $excel1900isLeapYear = False; }
@ -376,8 +648,17 @@ class SimpleXLSXGen {
$decade = substr($year,2,2);
$excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myExcelBaseDate + $excel1900isLeapYear;
$excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
return (float) $excelDate + $excelTime;
}
}
return (float) $excelDate + $excelTime;
}
public function setDefaultFont( $name ) {
$this->defaultFont = $name;
return $this;
}
public function setDefaultFontSize( $size ) {
$this->defaultFontSize = $size;
return $this;
}
public function esc( $str ) {
return str_replace( ['&', '<', '>', "\x03"], ['&amp;', '&lt;', '&gt;', ''], $str );
}
}

BIN
styles.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB