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

45 Commits

Author SHA1 Message Date
6d7608f8ca 1.3.10 2022-12-15 00:13:39 +06:00
80091bb9be 1.3.10 2022-12-15 00:04:53 +06:00
21b1d9a4b8 1.3.10 2022-12-14 23:47:14 +06:00
c1434378bc 1.3.10 2022-12-14 21:30:23 +06:00
75252a4a0c Merge pull request #79 from 2advance/patch-1
Update SimpleXLSXGen.php
2022-10-28 22:06:12 +06:00
f9d5480bb3 Update SimpleXLSXGen.php
Fix: Column width not working on Mac
2022-10-28 17:47:54 +02:00
aff0fa243d 1.2.16 2022-08-12 18:57:41 +06:00
82b0db1f8e 1.2.16 2022-08-06 23:13:06 +06:00
aef6ee4935 1.2.15 2022-07-28 18:26:11 +06:00
053574d1e1 1.2.15 2022-07-05 11:29:18 +06:00
f74163d311 1.2.15 2022-07-05 11:19:42 +06:00
0bf38275d7 1.2.14 2022-06-10 12:11:00 +06:00
459b1666e9 1.2.13 2022-06-10 12:07:39 +06:00
b63c66f8e9 1.2.13 2022-06-01 12:58:01 +06:00
1b5701a07f 1.2.13 2022-06-01 12:54:28 +06:00
199e5691e7 1.2.12 2022-05-17 12:10:24 +06:00
c54b314328 1.2.12 2022-05-17 12:06:30 +06:00
6db113f753 1.2.11 2022-05-17 12:03:35 +06:00
ff3f016358 1.2.11 2022-04-30 14:08:40 +06:00
bcd3586731 1.2.10 2022-04-30 14:04:13 +06:00
402c6b9417 1.2.10 2022-04-24 14:59:15 +06:00
5840fd5285 Merge pull request #58 from mrjemson/master
Added Font Color and Background Color Capabilities
2022-04-23 13:07:03 +06:00
4543922330 Updated examples 2022-04-23 11:34:13 +10:00
d49f8996df Switched to style tags 2022-04-23 11:33:17 +10:00
5309e6a002 Removed duplicate line 2022-04-22 23:21:40 +10:00
ab28bc319d Added missing line break 2022-04-22 23:19:38 +10:00
e145bd5777 Updated examples to include background fill 2022-04-22 23:16:28 +10:00
2ee7237016 Updated class to include background fill options 2022-04-22 23:15:35 +10:00
a0a932e2f5 Updated Styles Image for Background Fill 2022-04-22 23:14:42 +10:00
fc884044ac Color Code Clean Up 2022-04-22 18:03:17 +10:00
d84c842d38 Corrected const C_NORMAL value 2022-04-22 17:59:30 +10:00
0dafc8bf9e Fixes for color updates 2022-04-22 17:58:25 +10:00
82f19a9f35 Updated styles.png 2022-04-22 17:54:51 +10:00
139602c340 Update README.md 2022-04-22 17:51:35 +10:00
ac34d8f527 Added Font Color 2022-04-22 16:43:26 +10:00
c55d77c63e 1.1.12 2022-03-15 21:49:14 +06:00
c3d10db967 1.1.12 2022-03-15 21:47:33 +06:00
1c206d06bc 1.1.11 2022-02-12 03:25:59 +06:00
f0cbc32af9 1.1.11 2022-02-12 03:04:46 +06:00
121f1222c2 1.1.10 2022-02-05 18:32:10 +06:00
40eb704eb2 1.0.23 2022-02-01 02:50:32 +06:00
4005e8cbd1 Merge pull request #48 from appel/patch-1
added a ; in the Debug section.
2021-11-28 20:43:00 +06:00
9d82a43fe6 added a ; in the Debug section. 2021-11-28 08:48:15 -05:00
9a555eef9b 1.0.22 2021-10-29 03:37:04 +06:00
79ffbb5e30 1.0.21 2021-09-20 00:51:25 +06:00
8 changed files with 1116 additions and 655 deletions

3
.gitignore vendored
View File

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

View File

@ -1,35 +1,76 @@
# Changelog # Changelog
## 1.0.21 (2021-09-03) ## 1.3.10 (2022-12-14)
* added borders ```<style border="medium">Black Border</style>``` see colored [examples](https://github.com/shuchkin/simplexlsxgen#formatting)
* added formulas ```<f v="100">SUM(B1:B10)</f>``` see [examples](https://github.com/shuchkin/simplexlsxgen#data-types)
* added internal links ```<a href="sheet2!A1">Go to page 2</a>```
* added custom number formats ```<style nf="&quot;£&quot;#,##0.00">500</style>```
* added 3 currencies ```$data = [ ['$100.23', '2000.00 €', '1200.30 ₽'] ];```
## 1.2.16 (2022-08-12)
* added `autoFilter( $range )`
```php
$xlsx->autoFilter('A2:B10');
```
* fixed `0%` bug
## 1.2.15 (2022-07-05)
* added wrap words in long strings `<wraptext>long long line</wraptext>`
## 1.2.14 (2022-06-10)
* added example [JS array to Excel (AJAX)](https://github.com/shuchkin/simplexlsxgen#js-array-to-excel-ajax)
## 1.2.13 (2022-06-01)
* setColWidth(num_col_started_1, size_in_chars) - set column width
## 1.2.12 (2022-05-17)
* Vertical align (tags top,middle,bottom) `<bottom>12345</bottom>`
## 1.2.11 (2022-05-01)
* Row height `<style height="50">Custom row height 50</style>`
## 1.2.10 (2022-04-24)
* Added colors `<style color="#FFFF00" bgcolor="#00FF00">Yellow text on blue background</style>`, thx [mrjemson](https://github.com/mrjemson)
## 1.1.12 (2022-03-15)
* Added `$xlsx->mergeCells('A1:C1')`
## 1.1.11 (2022-02-05)
* sheet name maximum length is 31 chars, mb_substr used now
* license fixed
## 1.1.10 (2022-02-05)
* namespace added, use Shuchkin\SimpleXLSXGen
## 1.0.23 (2022-02-01)
* fixed dates if year < 1900 and time only cells, thx [fapth](https://github.com/shuchkin/simplexlsxgen/issues/51)
## 1.0.22 (2021-10-29)
* Escape \x00 and \x0B (vertical tab)
## 1.0.21 (2021-09-03)
* Fixed saveAs / downloadAs / etc methods more than once * Fixed saveAs / downloadAs / etc methods more than once
## 1.0.20 (2021-07-29) ## 1.0.20 (2021-07-29)
* Fixed sheet names duplicates (Page, Page (1), Page (2)...) * Fixed sheet names duplicates (Page, Page (1), Page (2)...)
## 1.0.19 (2021-07-28) ## 1.0.19 (2021-07-28)
* Fixed sheet names duplicates * Fixed sheet names duplicates
## 1.0.18 (2021-07-28) ## 1.0.18 (2021-07-28)
* Fixed email regex * Fixed email regex
## 1.0.17 (2021-07-28) ## 1.0.17 (2021-07-28)
* Fixed &quot; and &amp; in sheets names * Fixed &quot; and &amp; in sheets names
## 1.0.16 (2021-07-01) ## 1.0.16 (2021-07-01)
* Fixed &quot;&amp;&quot; in hyperlinks * Fixed &quot;&amp;&quot; in hyperlinks
## 1.0.15 (2021-06-22) ## 1.0.15 (2021-06-22)
* Fixed *mailto* hyperlinks detection * Fixed *mailto* hyperlinks detection
## 1.0.14 (2021-06-08) ## 1.0.14 (2021-06-08)
* Added *mailto* hyperlinks support (thx Howard Martin) * Added *mailto* hyperlinks support (thx Howard Martin)
```php ```php
SimpleXLSXGen::fromArray([ SimpleXLSXGen::fromArray([
@ -37,86 +78,65 @@ SimpleXLSXGen::fromArray([
])->saveAs('test.xlsx'); ])->saveAs('test.xlsx');
``` ```
## 1.0.13 (2021-05-29) ## 1.0.13 (2021-05-29)
* Fixed hyperlinks in several sheets * Fixed hyperlinks in several sheets
* Added [Opencollective donation link](https://opencollective.com/simplexlsx) * Added [Opencollective donation link](https://opencollective.com/simplexlsx)
## 1.0.12 (2021-05-19) ## 1.0.12 (2021-05-19)
* Fixed hyperlink regex * Fixed hyperlink regex
## 1.0.11 (2021-05-14) ## 1.0.11 (2021-05-14)
* Fixed 0.00% format, thx [marcrobledo](https://github.com/shuchkin/simplexlsxgen/pull/34), more examples in README.md * Fixed 0.00% format, thx [marcrobledo](https://github.com/shuchkin/simplexlsxgen/pull/34), more examples in README.md
## 1.0.10 (2021-05-03) ## 1.0.10 (2021-05-03)
Stable release Stable release
* Added hyperlinks and minimal formatting * Added hyperlinks and minimal formatting
## 0.9.25 (2021-02-26) ## 0.9.25 (2021-02-26)
* Added PHP Datetime object values in a cells * Added PHP Datetime object values in a cells
## 0.9.24 (2021-02-26) ## 0.9.24 (2021-02-26)
* Percent support * Percent support
## 0.9.23 (2021-01-25) ## 0.9.23 (2021-01-25)
* Fix local floats in XML * Fix local floats in XML
## 0.9.22 (2020-11-04) ## 0.9.22 (2020-11-04)
* Added multiple sheets support, thx [Savino59](https://github.com/Savino59), class ready for extend now * Added multiple sheets support, thx [Savino59](https://github.com/Savino59), class ready for extend now
## 0.9.21 (2020-10-17) ## 0.9.21 (2020-10-17)
* Updated images * Updated images
## 0.9.20 (2020-10-04) ## 0.9.20 (2020-10-04)
* Disable type detection if string started with chr(0) * Disable type detection if string started with chr(0)
## 0.9.19 (2020-08-23) ## 0.9.19 (2020-08-23)
* Numbers like SKU right aligned now * Numbers like SKU right aligned now
## 0.9.18 (2020-08-22) ## 0.9.18 (2020-08-22)
* Fixed fast shared strings index * Fixed fast shared strings index
## 0.9.17 (2020-08-21) ## 0.9.17 (2020-08-21)
* Fixed real numbers in 123.45 format detection, fast shared strings index (thx fredriksundin) * Fixed real numbers in 123.45 format detection, fast shared strings index (thx fredriksundin)
## 0.9.16 (2020-07-29) ## 0.9.16 (2020-07-29)
* Fixed time detection in HH:MM:SS format * Fixed time detection in HH:MM:SS format
## 0.9.15 (2020-07-14) ## 0.9.15 (2020-07-14)
* Escape of shared strings for special chars in cells [#1](https://github.com/shuchkin/simplexlsxgen/issues/1) * Escape of shared strings for special chars in cells [#1](https://github.com/shuchkin/simplexlsxgen/issues/1)
## 0.9.14 (2020-05-31) ## 0.9.14 (2020-05-31)
* Fixed num2name A-Z,AA-AZ column names, thx Ertan Yusufoglu * Fixed num2name A-Z,AA-AZ column names, thx Ertan Yusufoglu
## 0.9.13 (2020-05-21) ## 0.9.13 (2020-05-21)
* If string more 160 chars, save as inlineStr * If string more 160 chars, save as inlineStr
## 0.9.12 (2020-05-21) ## 0.9.12 (2020-05-21)
* Readme fixed * Readme fixed
## 0.9.11 (2020-05-21) ## 0.9.11 (2020-05-21)
* Removed XML unimportant attributes * Removed XML unimportant attributes
## 0.9.10 (2020-05-20) ## 0.9.10 (2020-05-20)
* Initial release * Initial release

108
README.md
View File

@ -1,10 +1,12 @@
# SimpleXLSXGen # 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) [<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/> Export data to Excel XLSX file. PHP XLSX generator. No external tools and libraries.
(!) XLSX reader [here](https://github.com/shuchkin/simplexlsx). - XLSX reader [here](https://github.com/shuchkin/simplexlsx)
- XLS reader [here](https://github.com/shuchkin/simplexls)
- CSV reader/writer [here](https://github.com/shuchkin/simplecsv)
**Sergey Shuchkin** <sergey.shuchkin@gmail.com> 2020-2021<br/> **Sergey Shuchkin** <sergey.shuchkin@gmail.com> 2020-2022<br/>
*Hey, bro, please ★ the package for my motivation :) and [donate](https://opencollective.com/simplexlsx) for more motivation!* *Hey, bro, please ★ the package for my motivation :) and [donate](https://opencollective.com/simplexlsx) for more motivation!*
@ -15,7 +17,7 @@ $books = [
[618260307, 'The Hobbit', 'J. R. R. Tolkien', 'Houghton Mifflin', 'USA'], [618260307, 'The Hobbit', 'J. R. R. Tolkien', 'Houghton Mifflin', 'USA'],
[908606664, 'Slinky Malinki', 'Lynley Dodd', 'Mallinson Rendel', 'NZ'] [908606664, 'Slinky Malinki', 'Lynley Dodd', 'Mallinson Rendel', 'NZ']
]; ];
$xlsx = SimpleXLSXGen::fromArray( $books ); $xlsx = Shuchkin\SimpleXLSXGen::fromArray( $books );
$xlsx->saveAs('books.xlsx'); // or downloadAs('books.xlsx') or $xlsx_content = (string) $xlsx $xlsx->saveAs('books.xlsx'); // or downloadAs('books.xlsx') or $xlsx_content = (string) $xlsx
``` ```
![XLSX screenshot](books.png) ![XLSX screenshot](books.png)
@ -37,13 +39,19 @@ $data = [
['Integer', 123], ['Integer', 123],
['Float', 12.35], ['Float', 12.35],
['Percent', '12%'], ['Percent', '12%'],
['Currency $', '$500.67'],
['Currency €', '200 €'],
['Currency ₽', '1200.30 ₽'],
['Currency (other)', '<style nf="&quot;£&quot;#,##0.00">500</style>'],
['Datetime', '2020-05-20 02:38:00'], ['Datetime', '2020-05-20 02:38:00'],
['Date', '2020-05-20'], ['Date', '2020-05-20'],
['Time', '02:38:00'], ['Time', '02:38:00'],
['Datetime PHP', new DateTime('2021-02-06 21:07:00')], ['Datetime PHP', new DateTime('2021-02-06 21:07:00')],
['String', 'Long UTF-8 String in autoresized column'], ['String', 'Long UTF-8 String in autoresized column'],
['Formula', '<f v="135.35">SUM(B1:B2)</f>'],
['Hyperlink', 'https://github.com/shuchkin/simplexlsxgen'], ['Hyperlink', 'https://github.com/shuchkin/simplexlsxgen'],
['Hyperlink + Anchor', '<a href="https://github.com/shuchkin/simplexlsxgen">SimpleXLSXGen</a>'], ['Hyperlink + Anchor', '<a href="https://github.com/shuchkin/simplexlsxgen">SimpleXLSXGen</a>'],
['Internal link', '<a href="sheet2!A1">Go to second page</a>'],
['RAW string', "\0" . '2020-10-04 16:02:00'] ['RAW string', "\0" . '2020-10-04 16:02:00']
]; ];
SimpleXLSXGen::fromArray($data)->saveAs('datatypes.xlsx'); SimpleXLSXGen::fromArray($data)->saveAs('datatypes.xlsx');
@ -61,14 +69,28 @@ $data = [
['Bold + Italic', '<b><i>12345.67</i></b>'], ['Bold + Italic', '<b><i>12345.67</i></b>'],
['Hyperlink', 'https://github.com/shuchkin/simplexlsxgen'], ['Hyperlink', 'https://github.com/shuchkin/simplexlsxgen'],
['Italic + Hyperlink + Anchor', '<i><a href="https://github.com/shuchkin/simplexlsxgen">SimpleXLSXGen</a></i>'], ['Italic + Hyperlink + Anchor', '<i><a href="https://github.com/shuchkin/simplexlsxgen">SimpleXLSXGen</a></i>'],
['Green', '<style color="#00FF00">12345.67</style>'],
['Bold Red Text', '<b><style color="#FF0000">12345.67</style></b>'],
['Blue Text and Yellow Fill', '<style bgcolor="#FFFF00" color="#0000FF">12345.67</style>'],
['Border color', '<style border="#000000">Black Thin Border</style>'],
['<top>Border style</top>','<style border="medium"><wraptext>none, thin, medium, dashed, dotted, thick, double, hair, mediumDashed, dashDot,mediumDashDot, dashDotDot, mediumDashDotDot, slantDashDot</wraptext></style>'],
['Border sides', '<style border="none dotted#0000FF medium#FF0000 double">Top No + Right Dotted + Bottom medium + Left double</style>'],
['Left', '<left>12345.67</left>'], ['Left', '<left>12345.67</left>'],
['Center', '<center>12345.67</center>'], ['Center', '<center>12345.67</center>'],
['Right', '<right>Right Text</right>'], ['Right', '<right>Right Text</right>'],
['Center + Bold', '<center><b>Name</b></center>'] ['Center + Bold', '<center><b>Name</b></center>'],
['Row height', '<style height="50">Row Height = 50</style>'],
['Top', '<style height="50"><top>Top</top></style>'],
['Middle + Center', '<style height="50"><middle><center>Middle + Center</center></middle></style>'],
['Bottom + Right', '<style height="50"><bottom><right>Bottom + Right</right></bottom></style>'],
['<center>MERGE CELLS MERGE CELLS MERGE CELLS MERGE CELLS MERGE CELLS</center>', null],
['<top>Word wrap</top>', "<wraptext>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book</wraptext>"]
]; ];
SimpleXLSXGen::fromArray($data) SimpleXLSXGen::fromArray($data)
->setDefaultFont('Courier New') ->setDefaultFont('Courier New')
->setDefaultFontSize(14) ->setDefaultFontSize(14)
->setColWidth(1, 35)
->mergeCells('A20:B20')
->saveAs('styles_and_tags.xlsx'); ->saveAs('styles_and_tags.xlsx');
``` ```
![XLSX screenshot](styles.png) ![XLSX screenshot](styles.png)
@ -76,20 +98,85 @@ SimpleXLSXGen::fromArray( $data )
### More examples ### More examples
```php ```php
// Fluid interface, output to browser for download // Fluid interface, output to browser for download
SimpleXLSXGen::fromArray( $books )->downloadAs('table.xlsx'); Shuchkin\SimpleXLSXGen::fromArray( $books )->downloadAs('table.xlsx');
// Fluid interface, multiple sheets // Fluid interface, multiple sheets
SimpleXLSXGen::fromArray( $books )->addSheet( $books2 )->download(); Shuchkin\SimpleXLSXGen::fromArray( $books )->addSheet( $books2 )->download();
// Alternative interface, sheet name, get xlsx content // Alternative interface, sheet name, get xlsx content
$xlsx_cache = (string) (new SimpleXLSXGen)->addSheet( $books, 'Modern style'); $xlsx_cache = (string) (new Shuchkin\SimpleXLSXGen)->addSheet( $books, 'Modern style');
// Classic interface // Classic interface
use Shuchkin\SimpleXLSXGen
$xlsx = new SimpleXLSXGen(); $xlsx = new SimpleXLSXGen();
$xlsx->addSheet( $books, 'Catalog 2021' ); $xlsx->addSheet( $books, 'Catalog 2021' );
$xlsx->addSheet( $books2, 'Stephen King catalog'); $xlsx->addSheet( $books2, 'Stephen King catalog');
$xlsx->downloadAs('books_2021.xlsx'); $xlsx->downloadAs('books_2021.xlsx');
exit(); exit();
// Autofilter
$xlsx->autoFilter('A1:B10');
```
### JS array to Excel (AJAX)
```php
<?php // array2excel.php
if (isset($_POST['array2excel'])) {
require __DIR__.'/simplexlsxgen/src/SimpleXLSXGen.php';
$data = json_decode($_POST['array2excel'], false);
\Shuchkin\SimpleXLSXGen::fromArray($data)->downloadAs('file.xlsx');
return;
}
?>
<html lang="en">
<head>
<title>JS array to Excel</title>
</head>
<script>
function array2excel() {
var books = [
["ISBN", "title", "author", "publisher", "ctry"],
[618260307, "The Hobbit", "J. R. R. Tolkien", "Houghton Mifflin", "USA"],
[908606664, "Slinky Malinki", "Lynley Dodd", "Mallinson Rendel", "NZ"]
];
var json = JSON.stringify(books);
var request = new XMLHttpRequest();
request.onload = function () {
if (this.status === 200) {
var file = new Blob([this.response], {type: this.getResponseHeader('Content-Type')});
var fileURL = URL.createObjectURL(file);
var filename = "", m;
var disposition = this.getResponseHeader('Content-Disposition');
if (disposition && (m = /"([^"]+)"/.exec(disposition)) !== null) {
filename = m[1];
}
var a = document.createElement("a");
if (typeof a.download === 'undefined') {
window.location = fileURL;
} else {
a.href = fileURL;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
alert("Error: " + this.status + " " + this.statusText);
}
}
request.open('POST', "array2excel.php");
request.responseType = "blob";
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("array2excel=" + encodeURIComponent(json));
}
</script>
<body>
<input type="button" onclick="array2excel()" value="array2excel" />
</body>
</html>
``` ```
## Debug ## Debug
@ -99,6 +186,7 @@ ini_set('display_errors', 1 );
$data = [ $data = [
['Debug', 123] ['Debug', 123]
] ];
SimpleXLSXGen::fromArray( $data )->saveAs('debug.xlsx');
Shuchkin\SimpleXLSXGen::fromArray( $data )->saveAs('debug.xlsx');
``` ```

View File

@ -17,6 +17,7 @@
] ]
}, },
"require": { "require": {
"php": ">=5.4",
"ext-mbstring": "*", "ext-mbstring": "*",
"ext-zlib": "*" "ext-zlib": "*"
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2014 Lukas Martinelli Copyright (c) 2020-2022 Sergey Shuchkin sergey.shuchkin@gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -1,20 +1,32 @@
<?php <?php /** @noinspection ReturnTypeCanBeDeclaredInspection */
/** @noinspection PhpMissingReturnTypeInspection */
/** @noinspection NullCoalescingOperatorCanBeUsedInspection */
/** @noinspection PhpIssetCanBeReplacedWithCoalesceInspection */
namespace Shuchkin;
/** /**
* Class SimpleXLSXGen * Class SimpleXLSXGen
* Export data to MS Excel. PHP XLSX generator * Export data to MS Excel. PHP XLSX generator
* Author: sergey.shuchkin@gmail.com * Author: sergey.shuchkin@gmail.com
*/ */
class SimpleXLSXGen
class SimpleXLSXGen { {
public $curSheet; public $curSheet;
protected $defaultFont; protected $defaultFont;
protected $defaultFontSize; protected $defaultFontSize;
protected $sheets; protected $sheets;
protected $template; protected $template;
protected $F, $F_KEYS; // fonts protected $NF; // numFmts
protected $XF, $XF_KEYS; // cellXfs protected $NF_KEYS;
protected $SI, $SI_KEYS; // shared strings protected $XF; // cellXfs
protected $XF_KEYS;
protected $BR_STYLE;
protected $SI; // shared strings
protected $SI_KEYS;
protected $extLinkId;
const N_NORMAL = 0; // General const N_NORMAL = 0; // General
const N_INT = 1; // 0 const N_INT = 1; // 0
const N_DEC = 2; // 0.00 const N_DEC = 2; // 0.00
@ -22,6 +34,9 @@ class SimpleXLSXGen {
const N_PRECENT_DEC = 10; // 0.00% const N_PRECENT_DEC = 10; // 0.00%
const N_DATE = 14; // mm-dd-yy const N_DATE = 14; // mm-dd-yy
const N_TIME = 20; // h:mm const N_TIME = 20; // h:mm
const N_RUB = 164;
const N_DOLLAR = 165;
const N_EURO = 166;
const N_DATETIME = 22; // m/d/yy h:mm const N_DATETIME = 22; // m/d/yy h:mm
const F_NORMAL = 0; const F_NORMAL = 0;
const F_HYPERLINK = 1; const F_HYPERLINK = 1;
@ -29,22 +44,80 @@ class SimpleXLSXGen {
const F_ITALIC = 4; const F_ITALIC = 4;
const F_UNDERLINE = 8; const F_UNDERLINE = 8;
const F_STRIKE = 16; const F_STRIKE = 16;
const F_COLOR = 32;
const FL_NONE = 0; // none
const FL_SOLID = 1; // solid
const FL_MEDIUM_GRAY = 2; // mediumGray
const FL_DARK_GRAY = 4; // darkGray
const FL_LIGHT_GRAY = 8; // lightGray
const FL_GRAY_125 = 16; // gray125
const FL_COLOR = 32;
const A_DEFAULT = 0; const A_DEFAULT = 0;
const A_LEFT = 1; const A_LEFT = 1;
const A_RIGHT = 2; const A_RIGHT = 2;
const A_CENTER = 3; const A_CENTER = 4;
const A_TOP = 8;
const A_MIDDLE = 16;
const A_BOTTOM = 32;
const A_WRAPTEXT = 64;
const B_NONE = 0;
const B_THIN = 1;
const B_MEDIUM = 2;
//const
const B_DASHED = 3;
const B_DOTTED = 4;
const B_THICK = 5;
const B_DOUBLE = 6;
const B_HAIR = 7;
const B_MEDIUM_DASHED = 8;
const B_DASH_DOT = 9;
const B_MEDIUM_DASH_DOT = 10;
const B_DASH_DOT_DOT = 11;
const B_MEDIUM_DASH_DOT_DOT = 12;
const B_SLANT_DASH_DOT = 13;
public function __construct()
public function __construct() { {
$this->curSheet = -1; $this->curSheet = -1;
$this->defaultFont = 'Calibri'; $this->defaultFont = 'Calibri';
$this->sheets = [ ['name' => 'Sheet1', 'rows' => [], 'hyperlinks' => [] ] ]; $this->sheets = [['name' => 'Sheet1', 'rows' => [], 'hyperlinks' => [], 'mergecells' => [], 'colwidth' => [], 'autofilter' => '']];
$this->extLinkId = 0;
$this->SI = []; // sharedStrings index $this->SI = []; // sharedStrings index
$this->SI_KEYS = []; // & keys $this->SI_KEYS = []; // & keys
$this->F = [ self::F_NORMAL ]; // fonts
$this->F_KEYS = [0]; // & keys // https://c-rex.net/projects/samples/ooxml/e1/Part4/OOXML_P4_DOCX_numFmts_topic_ID0E6KK6.html
$this->XF = [ [self::N_NORMAL, self::F_NORMAL, self::A_DEFAULT] ]; // styles $this->NF = [
$this->XF_KEYS = ['N0F0A0' => 0 ]; // & keys self::N_RUB => '#,##0.00\ "₽"',
self::N_DOLLAR => '[$$-1]#,##0.00',
self::N_EURO => '#,##0.00\ [$€-1]'
];
$this->NF_KEYS = array_flip($this->NF);
$this->BR_STYLE = [
self::B_NONE => 'none',
self::B_THIN => 'thin',
self::B_MEDIUM => 'medium',
self::B_DASHED => 'dashed',
self::B_DOTTED => 'dotted',
self::B_THICK => 'thick',
self::B_DOUBLE => 'double',
self::B_HAIR => 'hair',
self::B_MEDIUM_DASHED => 'mediumDashed',
self::B_DASH_DOT => 'dashDot',
self::B_MEDIUM_DASH_DOT => 'mediumDashDot',
self::B_DASH_DOT_DOT => 'dashDotDot',
self::B_MEDIUM_DASH_DOT_DOT => 'mediumDashDotDot',
self::B_SLANT_DASH_DOT => 'slantDashDot'
];
$this->XF = [ // styles 0 - num fmt, 1 - align, 2 - font, 3 - fill, 4 - font color, 5 - bgcolor, 6 - border
[self::N_NORMAL, self::A_DEFAULT, self::F_NORMAL, self::FL_NONE, 0, 0, ''],
[self::N_NORMAL, self::A_DEFAULT, self::F_NORMAL, self::FL_GRAY_125, 0, 0, ''], // hack
];
$this->XF_KEYS[implode('-', $this->XF[0])] = 0; // & keys
$this->XF_KEYS[implode('-', $this->XF[1])] = 1;
$this->template = [ $this->template = [
'_rels/.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?> '_rels/.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
@ -71,16 +144,17 @@ class SimpleXLSXGen {
'xl/worksheets/sheet1.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 'xl/worksheets/sheet1.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
><dimension ref="{REF}"/>{COLS}<sheetData>{ROWS}</sheetData>{HYPERLINKS}</worksheet>', ><dimension ref="{REF}"/>{COLS}<sheetData>{ROWS}</sheetData>{AUTOFILTER}{MERGECELLS}{HYPERLINKS}</worksheet>',
'xl/worksheets/_rels/sheet1.xml.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?> '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>', <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{HYPERLINKS}</Relationships>',
'xl/sharedStrings.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?> '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>', <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"?> 'xl/styles.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"> <styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
{NUMFMTS}
{FONTS} {FONTS}
<fills count="1"><fill><patternFill patternType="none"/></fill></fills> {FILLS}
<borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders> {BORDERS}
<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" /></cellStyleXfs> <cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" /></cellStyleXfs>
{XF} {XF}
<cellStyles count="1"> <cellStyles count="1">
@ -109,24 +183,31 @@ class SimpleXLSXGen {
// <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> // <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> // <si><t>Простой шаблон</t></si><si><t>Будем делать генератор</t></si>
} }
public static function fromArray( array $rows, $sheetName = null ) {
$xlsx = new static(); public static function fromArray(array $rows, $sheetName = null)
return $xlsx->addSheet( $rows, $sheetName ); {
return (new static())->addSheet($rows, $sheetName);
} }
public function addSheet( array $rows, $name = null ) { public function addSheet(array $rows, $name = null)
{
$this->curSheet++; $this->curSheet++;
if ($name === null) { // autogenerated sheet names if ($name === null) { // autogenerated sheet names
$name = 'Sheet' . ($this->curSheet + 1); $name = 'Sheet' . ($this->curSheet + 1);
} else { } else {
$name = mb_substr($name, 0, 31);
$names = []; $names = [];
foreach ($this->sheets as $sh) { foreach ($this->sheets as $sh) {
$names[ strtoupper( $sh['name']) ] = 1; $names[mb_strtoupper($sh['name'])] = 1;
} }
for ($i = 0; $i < 100; $i++) { for ($i = 0; $i < 100; $i++) {
$new_name = ($i === 0) ? $name : $name .' ('.$i.')'; $postfix = ' (' . $i . ')';
$NEW_NAME = strtoupper( $new_name ); $new_name = ($i === 0) ? $name : $name . $postfix;
if (mb_strlen($new_name) > 31) {
$new_name = mb_substr($name, 0, 31 - mb_strlen($postfix)) . $postfix;
}
$NEW_NAME = mb_strtoupper($new_name);
if (!isset($names[$NEW_NAME])) { if (!isset($names[$NEW_NAME])) {
$name = $new_name; $name = $new_name;
break; break;
@ -134,9 +215,9 @@ class SimpleXLSXGen {
} }
} }
$this->sheets[$this->curSheet] = ['name' => $name, 'hyperlinks' => []]; $this->sheets[$this->curSheet] = ['name' => $name, 'hyperlinks' => [], 'mergecells' => [], 'colwidth' => [], 'autofilter' => ''];
if ( is_array( $rows ) && isset( $rows[0] ) && is_array($rows[0]) ) { if (isset($rows[0]) && is_array($rows[0])) {
$this->sheets[$this->curSheet]['rows'] = $rows; $this->sheets[$this->curSheet]['rows'] = $rows;
} else { } else {
$this->sheets[$this->curSheet]['rows'] = []; $this->sheets[$this->curSheet]['rows'] = [];
@ -144,7 +225,8 @@ class SimpleXLSXGen {
return $this; return $this;
} }
public function __toString() { public function __toString()
{
$fh = fopen('php://memory', 'wb'); $fh = fopen('php://memory', 'wb');
if (!$fh) { if (!$fh) {
return ''; return '';
@ -160,7 +242,8 @@ class SimpleXLSXGen {
return (string)fread($fh, $size); return (string)fread($fh, $size);
} }
public function saveAs( $filename ) { public function saveAs($filename)
{
$fh = fopen($filename, 'wb'); $fh = fopen($filename, 'wb');
if (!$fh) { if (!$fh) {
return false; return false;
@ -174,11 +257,13 @@ class SimpleXLSXGen {
return true; return true;
} }
public function download() { public function download()
{
return $this->downloadAs(gmdate('YmdHi') . '.xlsx'); return $this->downloadAs(gmdate('YmdHi') . '.xlsx');
} }
public function downloadAs( $filename ) { public function downloadAs($filename)
{
$fh = fopen('php://memory', 'wb'); $fh = fopen('php://memory', 'wb');
if (!$fh) { if (!$fh) {
return false; return false;
@ -206,7 +291,8 @@ class SimpleXLSXGen {
return true; return true;
} }
protected function _write( $fh ) { protected function _write($fh)
{
$dirSignatureE = "\x50\x4b\x05\x06"; // end of central dir signature $dirSignatureE = "\x50\x4b\x05\x06"; // end of central dir signature
@ -239,8 +325,7 @@ class SimpleXLSXGen {
$template = str_replace('{SHEETS}', $s, $template); $template = str_replace('{SHEETS}', $s, $template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template); $this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++; $entries++;
} } elseif ($cfilename === 'docProps/core.xml') {
elseif ( $cfilename === 'docProps/core.xml' ) {
$template = str_replace('{DATE}', gmdate('Y-m-d\TH:i:s\Z'), $template); $template = str_replace('{DATE}', gmdate('Y-m-d\TH:i:s\Z'), $template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template); $this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++; $entries++;
@ -263,12 +348,14 @@ class SimpleXLSXGen {
$xml = null; $xml = null;
} elseif ($cfilename === 'xl/worksheets/_rels/sheet1.xml.rels') { } elseif ($cfilename === 'xl/worksheets/_rels/sheet1.xml.rels') {
foreach ($this->sheets as $k => $v) { foreach ($this->sheets as $k => $v) {
if ( count($v['hyperlinks'])) { if ($this->extLinkId) {
$RH = []; $RH = [];
$filename = 'xl/worksheets/_rels/sheet' . ($k + 1) . '.xml.rels'; $filename = 'xl/worksheets/_rels/sheet' . ($k + 1) . '.xml.rels';
foreach ($v['hyperlinks'] as $h) { foreach ($v['hyperlinks'] as $h) {
if ($h['ID']) {
$RH[] = '<Relationship Id="' . $h['ID'] . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="' . $this->esc($h['H']) . '" TargetMode="External"/>'; $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); $xml = str_replace('{HYPERLINKS}', implode("\r\n", $RH), $template);
$this->_writeEntry($fh, $cdrec, $filename, $xml); $this->_writeEntry($fh, $cdrec, $filename, $xml);
$entries++; $entries++;
@ -281,7 +368,7 @@ class SimpleXLSXGen {
foreach ($this->sheets as $k => $v) { foreach ($this->sheets as $k => $v) {
$TYPES[] = '<Override PartName="/xl/worksheets/sheet' . ($k + 1) . $TYPES[] = '<Override PartName="/xl/worksheets/sheet' . ($k + 1) .
'.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'; '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
if (count( $v['hyperlinks'])) { if ($this->extLinkId) {
$TYPES[] = '<Override PartName="/xl/worksheets/_rels/sheet' . ($k + 1) . '.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'; $TYPES[] = '<Override PartName="/xl/worksheets/_rels/sheet' . ($k + 1) . '.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
} }
} }
@ -289,30 +376,136 @@ class SimpleXLSXGen {
$this->_writeEntry($fh, $cdrec, $cfilename, $template); $this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++; $entries++;
} elseif ($cfilename === 'xl/styles.xml') { } elseif ($cfilename === 'xl/styles.xml') {
$FONTS = ['<fonts count="'.count($this->F).'">']; $NF = $XF = $FONTS = $F_KEYS = $FILLS = $FL_KEYS = [];
foreach ( $this->F as $f ) { $BR = ['<border><left/><right/><top/><bottom/><diagonal/></border>'];
$BR_KEYS = [0 => 0];
foreach ($this->NF as $k => $v) {
$NF[] = '<numFmt numFmtId="' . $k . '" formatCode="' . htmlspecialchars($v, ENT_QUOTES) . '"/>';
}
foreach ($this->XF as $xf) {
// 0 - num fmt, 1 - align, 2 - font, 3 - fill, 4 - font color, 5 - bgcolor, 6 - border
// fonts
$F_KEY = $xf[2] . '-' . $xf[4];
if (isset($F_KEYS[$F_KEY])) {
$F_ID = $F_KEYS[$F_KEY];
} else {
$F_ID = $F_KEYS[$F_KEY] = count($FONTS);
$FONTS[] = '<font><name val="' . $this->defaultFont . '"/><family val="2"/>' $FONTS[] = '<font><name val="' . $this->defaultFont . '"/><family val="2"/>'
. ($this->defaultFontSize ? '<sz val="' . $this->defaultFontSize . '"/>' : '') . ($this->defaultFontSize ? '<sz val="' . $this->defaultFontSize . '"/>' : '')
.( $f & self::F_BOLD ? '<b/>' : '') . ($xf[2] & self::F_BOLD ? '<b/>' : '')
.( $f & self::F_ITALIC ? '<i/>' : '') . ($xf[2] & self::F_ITALIC ? '<i/>' : '')
.( $f & self::F_UNDERLINE ? '<u/>' : '') . ($xf[2] & self::F_UNDERLINE ? '<u/>' : '')
.( $f & self::F_STRIKE ? '<strike/>' : '') . ($xf[2] & self::F_STRIKE ? '<strike/>' : '')
.( $f & self::F_HYPERLINK ? '<color rgb="FF0563C1"/><u/>' : '') . ($xf[2] & self::F_HYPERLINK ? '<u/>' : '')
. ($xf[2] & self::F_COLOR ? '<color rgb="' . $xf[4] . '"/>' : '')
. '</font>'; . '</font>';
} }
$FONTS[] = '</fonts>'; // fills
$XF = ['<cellXfs count="'.count($this->XF).'">']; $FL_KEY = $xf[3] . '-' . $xf[5];
foreach( $this->XF as $xf ) { if (isset($FL_KEYS[$FL_KEY])) {
$align = ($xf[2] === self::A_LEFT ? ' applyAlignment="1"><alignment horizontal="left"/>' : '') $FL_ID = $FL_KEYS[$FL_KEY];
.($xf[2] === self::A_RIGHT ? ' applyAlignment="1"><alignment horizontal="right"/>' : '') } else {
.($xf[2] === self::A_CENTER ? ' applyAlignment="1"><alignment horizontal="center"/>' : ''); $FL_ID = $FL_KEYS[$FL_KEY] = count($FILLS);
$XF[] = '<xf numFmtId="'.$xf[0].'" fontId="'.$xf[1].'" fillId="0" borderId="0" xfId="0"' $FILLS[] = '<fill><patternFill patternType="'
.($xf[0] > 0 ? ' applyNumberFormat="1"' : '') . ($xf[3] === 0 ? 'none' : '')
.($align ? $align . '</xf>' : '/>'); . ($xf[3] & self::FL_SOLID ? 'solid' : '')
. ($xf[3] & self::FL_MEDIUM_GRAY ? 'mediumGray' : '')
. ($xf[3] & self::FL_DARK_GRAY ? 'darkGray' : '')
. ($xf[3] & self::FL_LIGHT_GRAY ? 'lightGray' : '')
. ($xf[3] & self::FL_GRAY_125 ? 'gray125' : '')
. '"'
. ($xf[3] & self::FL_COLOR ? '><fgColor rgb="' . $xf[5] . '"/><bgColor indexed="64"/></patternFill>' : ' />')
. '</fill>';
}
$align = ($xf[1] & self::A_LEFT ? ' horizontal="left"' : '')
. ($xf[1] & self::A_RIGHT ? ' horizontal="right"' : '')
. ($xf[1] & self::A_CENTER ? ' horizontal="center"' : '')
. ($xf[1] & self::A_TOP ? ' vertical="top"' : '')
. ($xf[1] & self::A_MIDDLE ? ' vertical="center"' : '')
. ($xf[1] & self::A_BOTTOM ? ' vertical="bottom"' : '')
. ($xf[1] & self::A_WRAPTEXT ? ' wrapText="1"' : '');
// border
$BR_ID = 0;
if ($xf[6] !== '') {
$b = $xf[6];
if (isset($BR_KEYS[$b])) {
$BR_ID = $BR_KEYS[$b];
} else {
$BR_ID = count($BR_KEYS);
$BR_KEYS[$b] = $BR_ID;
$border = '<border>';
$ba = explode(' ', $b);
if (!isset($ba[1])) {
$ba[] = $ba[0];
$ba[] = $ba[0];
$ba[] = $ba[0];
}
if (!isset($ba[4])) { // diagonal
$ba[] = 'none';
}
$sides = [ 'left' => 3, 'right' => 1, 'top' => 0, 'bottom' => 2, 'diagonal' => 4];
foreach ($sides as $side => $idx) {
$s = 'thin';
$c = '';
$va = explode('#', $ba[$idx]);
if (isset($va[1])) {
$s = $va[0] === '' ? 'thin' : $va[0];
$c = $va[1];
} elseif (in_array($va[0], $this->BR_STYLE, true)) {
$s = $va[0];
} else {
$c = $va[0];
}
if (strlen($c) === 6) {
$c = 'FF' . $c;
}
if ($s && $s !== 'none') {
$border .= '<' . $side . ' style="' . $s . '">'
. '<color ' . ($c === '' ? 'auto="1"' : 'rgb="' . $c . '"') . '/>'
. '</' . $side . '>';
} else {
$border .= '<' . $side . '/>';
}
} }
$border .= '</border>';
$BR[] = $border;
}
}
$XF[] = '<xf numFmtId="' . $xf[0] . '" fontId="' . $F_ID . '" fillId="' . $FL_ID . '" borderId="' . $BR_ID . '" xfId="0"'
. ($xf[0] > 0 ? ' applyNumberFormat="1"' : '')
. ($F_ID > 0 ? ' applyFont="1"' : '')
. ($FL_ID > 0 ? ' applyFill="1"' : '')
. ($BR_ID > 0 ? ' applyBorder="1"' : '')
. ($align ? ' applyAlignment="1"><alignment' . $align . '/></xf>' : '/>');
}
// wrap collections
array_unshift($NF, '<numFmts count="' . count($NF) . '">');
$NF[] = '</numFmts>';
array_unshift($XF, '<cellXfs count="' . count($XF) . '">');
$XF[] = '</cellXfs>'; $XF[] = '</cellXfs>';
$template = str_replace(['{FONTS}','{XF}'], [implode("\r\n", $FONTS), implode("\r\n", $XF)], $template); array_unshift($FONTS, '<fonts count="' . count($FONTS) . '">');
$FONTS[] = '</fonts>';
array_unshift($FILLS, '<fills count="' . count($FILLS) . '">');
$FILLS[] = '</fills>';
array_unshift($BR, '<borders count="' . count($BR) . '">');
$BR[] = '</borders>';
$template = str_replace(
['{NUMFMTS}', '{FONTS}', '{XF}', '{FILLS}', '{BORDERS}'],
[implode("\r\n", $NF), implode("\r\n", $FONTS), implode("\r\n", $XF), implode("\r\n", $FILLS), implode("\r\n", $BR)],
$template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template); $this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++; $entries++;
} else { } else {
@ -337,7 +530,8 @@ class SimpleXLSXGen {
return true; return true;
} }
protected function _writeEntry($fh, &$cdrec, $cfilename, $data) { protected function _writeEntry($fh, &$cdrec, $cfilename, $data)
{
$zipSignature = "\x50\x4b\x03\x04"; // local file header signature $zipSignature = "\x50\x4b\x03\x04"; // local file header signature
$dirSignature = "\x50\x4b\x01\x02"; // central dir header signature $dirSignature = "\x50\x4b\x01\x02"; // central dir header signature
@ -416,7 +610,8 @@ class SimpleXLSXGen {
$cdrec .= $e['comments']; $cdrec .= $e['comments'];
} }
protected function _sheetToXML($idx, $template) { protected function _sheetToXML($idx, $template)
{
// locale floats fr_FR 1.234,56 -> 1234.56 // locale floats fr_FR 1.234,56 -> 1234.56
$_loc = setlocale(LC_NUMERIC, 0); $_loc = setlocale(LC_NUMERIC, 0);
setlocale(LC_NUMERIC, 'C'); setlocale(LC_NUMERIC, 'C');
@ -428,21 +623,24 @@ class SimpleXLSXGen {
$COL = []; $COL = [];
foreach ($this->sheets[$idx]['rows'] as $r) { foreach ($this->sheets[$idx]['rows'] as $r) {
$CUR_ROW++; $CUR_ROW++;
$row = '<row r="'.$CUR_ROW.'">'; $row = '';
$CUR_COL = 0; $CUR_COL = 0;
$RH = 0; // row height
foreach ($r as $v) { foreach ($r as $v) {
$CUR_COL++; $CUR_COL++;
if (!isset($COL[$CUR_COL])) { if (!isset($COL[$CUR_COL])) {
$COL[$CUR_COL] = 0; $COL[$CUR_COL] = 0;
} }
$cname = $this->num2name($CUR_COL) . $CUR_ROW;
if ($v === null || $v === '') { if ($v === null || $v === '') {
$row .= '<c r="' . $cname . '"/>';
continue; continue;
} }
$cname = $this->num2name($CUR_COL) . $CUR_ROW; $ct = $cv = $cf = null;
$N = $A = $F = $FL = $C = $BG = 0;
$ct = $cv = null; $BR = '';
$N = $F = $A = 0;
if (is_string($v)) { if (is_string($v)) {
@ -463,6 +661,33 @@ class SimpleXLSXGen {
if (strpos($v, '<s>') !== false) { if (strpos($v, '<s>') !== false) {
$F += self::F_STRIKE; $F += self::F_STRIKE;
} }
if (preg_match('/<style([^>]+)>/', $v, $m)) {
if (preg_match('/ color="([^"]+)"/', $m[1], $m2)) {
$F += self::F_COLOR;
$c = ltrim($m2[1], '#');
$C = strlen($c) === 8 ? $c : ('FF' . $c);
}
if (preg_match('/ bgcolor="([^"]+)"/', $m[1], $m2)) {
$FL += self::FL_COLOR;
$c = ltrim($m2[1], '#');
$BG = strlen($c) === 8 ? $c : ('FF' . $c);
}
if (preg_match('/ height="([^"]+)"/', $m[1], $m2)) {
$RH = $m2[1];
}
if (preg_match('/ nf="([^"]+)"/', $m[1], $m2)) {
$c = htmlspecialchars_decode($m2[1], ENT_QUOTES);
$N = $this->getNumFmtId($c);
}
if (preg_match('/ border="([^"]+)"/', $m[1], $m2)) {
$b = htmlspecialchars_decode($m2[1], ENT_QUOTES);
if ($b && $b !== 'none') {
$BR = $b;
}
}
}
if (strpos($v, '<left>') !== false) { if (strpos($v, '<left>') !== false) {
$A += self::A_LEFT; $A += self::A_LEFT;
} }
@ -472,19 +697,47 @@ class SimpleXLSXGen {
if (strpos($v, '<right>') !== false) { if (strpos($v, '<right>') !== false) {
$A += self::A_RIGHT; $A += self::A_RIGHT;
} }
if (strpos($v, '<top>') !== false) {
$A += self::A_TOP;
}
if (strpos($v, '<middle>') !== false) {
$A += self::A_MIDDLE;
}
if (strpos($v, '<bottom>') !== false) {
$A += self::A_BOTTOM;
}
if (strpos($v, '<wraptext>') !== false) {
$A += self::A_WRAPTEXT;
}
if (preg_match('/<a href="(https?:\/\/[^"]+)">(.*?)<\/a>/i', $v, $m)) { if (preg_match('/<a href="(https?:\/\/[^"]+)">(.*?)<\/a>/i', $v, $m)) {
$h = explode('#', $m[1]); $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] : '']; $this->extLinkId++;
$F = self::F_HYPERLINK; // Hyperlink $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, '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)) { 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' => '']; $this->extLinkId++;
$F = self::F_HYPERLINK; // mailto hyperlink $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, 'R' => $cname, 'H' => $m[1], 'L' => ''];
$F += self::F_HYPERLINK; // mailto hyperlink
} }
if (preg_match('/<a href="([^"]+![^"]+)">(.*?)<\/a>/i', $v, $m)) {
$this->sheets[$idx]['hyperlinks'][] = ['ID' => null, 'R' => $cname, 'H' => null, 'L' => $m[1]];
$F += self::F_HYPERLINK; // internal hyperlink
}
if (preg_match('/<f([^>]*)>/', $v, $m)) {
$cf = strip_tags($v);
$v = 'formula';
if (preg_match('/ v="([^"]+)"/', $m[1], $m2)) {
$v = $m2[1];
}
} else {
$v = strip_tags($v); $v = strip_tags($v);
}
} // tags } // tags
$vl = mb_strlen($v); $vl = mb_strlen($v);
if ( $v === '0' || preg_match( '/^[-+]?[1-9]\d{0,14}$/', $v ) ) { // Integer as General if ($N) {
$cv = ltrim($v, '+');
} elseif ($v === '0' || preg_match('/^[-+]?[1-9]\d{0,14}$/', $v)) { // Integer as General
$cv = ltrim($v, '+'); $cv = ltrim($v, '+');
if ($vl > 10) { if ($vl > 10) {
$N = self::N_INT; // [1] 0 $N = self::N_INT; // [1] 0
@ -494,6 +747,16 @@ class SimpleXLSXGen {
if (strlen($m[2]) < 3) { if (strlen($m[2]) < 3) {
$N = self::N_DEC; $N = self::N_DEC;
} }
} elseif (preg_match('/^\$[-+]?[0-9\.]+$/', $v)) { // currency $?
$N = self::N_DOLLAR;
$cv = ltrim($v, '+$');
} elseif (preg_match('/^[-+]?[0-9\.]+( ₽| €)$/u', $v, $m)) { // currency ₽ €?
if ($m[1] === ' ₽') {
$N = self::N_RUB;
} elseif ($m[1] === ' €') {
$N = self::N_EURO;
}
$cv = trim($v, ' +₽€');
} elseif (preg_match('/^([-+]?\d+)%$/', $v, $m)) { } elseif (preg_match('/^([-+]?\d+)%$/', $v, $m)) {
$cv = round($m[1] / 100, 2); $cv = round($m[1] / 100, 2);
$N = self::N_PERCENT_INT; // [9] 0% $N = self::N_PERCENT_INT; // [9] 0%
@ -511,26 +774,35 @@ class SimpleXLSXGen {
$N = self::N_TIME; // time $N = self::N_TIME; // time
} elseif (preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$/', $v, $m)) { } 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]); $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 $N = ((int)$m[1] === 0) ? self::N_TIME : 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)) { } 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]); $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 $N = self::N_DATETIME; // [22] m/d/yy h:mm
} elseif (preg_match('/^[0-9+-.]+$/', $v)) { // Long ? } elseif (preg_match('/^[0-9+-.]+$/', $v)) { // Long ?
$A = self::A_RIGHT; $A += ($A & (self::A_LEFT | self::A_CENTER)) ? 0 : self::A_RIGHT;
} elseif (preg_match('/^https?:\/\/\S+$/i', $v)) { } elseif (preg_match('/^https?:\/\/\S+$/i', $v)) {
$h = explode('#', $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] : '']; $this->extLinkId++;
$F = self::F_HYPERLINK; // Hyperlink $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, '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)) { } 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' => '']; $this->extLinkId++;
$F = self::F_HYPERLINK; // Hyperlink $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, 'R' => $cname, 'H' => 'mailto:' . $v, 'L' => ''];
$F += self::F_HYPERLINK; // Hyperlink
}
if (($N === self::N_DATE || $N === self::N_DATETIME) && $cv < 0) {
$cv = null;
$N = 0;
} }
} }
if ( !$cv) { if ($cv === null) {
$v = $this->esc($v); $v = $this->esc($v);
if ( mb_strlen( $v ) > 160 ) { if ($cf) {
$ct = 'str';
$cv = $v;
} elseif (mb_strlen($v) > 160) {
$ct = 'inlineStr'; $ct = 'inlineStr';
$cv = $v; $cv = $v;
} else { } else {
@ -553,7 +825,7 @@ class SimpleXLSXGen {
} elseif (is_float($v)) { } elseif (is_float($v)) {
$vl = mb_strlen((string)$v); $vl = mb_strlen((string)$v);
$cv = $v; $cv = $v;
} elseif ( $v instanceof DateTime ) { } elseif ($v instanceof \DateTime) {
$vl = 16; $vl = 16;
$cv = $this->date2excel($v->format('Y'), $v->format('m'), $v->format('d'), $v->format('H'), $v->format('i'), $v->format('s')); $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 $N = self::N_DATETIME; // [22] m/d/yy h:mm
@ -564,57 +836,86 @@ class SimpleXLSXGen {
$COL[$CUR_COL] = max($vl, $COL[$CUR_COL]); $COL[$CUR_COL] = max($vl, $COL[$CUR_COL]);
$cs = 0; $cs = 0;
if ( $N + $F + $A > 0 ) {
if ( isset($this->F_KEYS[ $F ] ) ) { if (($N + $A + $F + $FL > 0) || $BR !== '') {
$cf = $this->F_KEYS[ $F ];
} else { if ($FL === self::FL_COLOR) {
$cf = count($this->F); $FL += self::FL_SOLID;
$this->F_KEYS[$F] = $cf;
$this->F[] = $F;
} }
$NFA = 'N' . $N . 'F' . $cf . 'A' . $A; if (($F & self::F_HYPERLINK) && !($F & self::F_COLOR)) {
if ( isset( $this->XF_KEYS[ $NFA ] ) ) { $F += self::F_COLOR;
$cs = $this->XF_KEYS[ $NFA ]; $C = 'FF0563C1';
}
$XF_KEY = $N . '-' . $A . '-' . $F . '-' . $FL . '-' . $C . '-' . $BG . '-' . $BR;
// echo $cname .'='.$XF_KEY.PHP_EOL;
if (isset($this->XF_KEYS[$XF_KEY])) {
$cs = $this->XF_KEYS[$XF_KEY];
} }
if ($cs === 0) { if ($cs === 0) {
$cs = count($this->XF); $cs = count($this->XF);
$this->XF_KEYS[ $NFA ] = $cs; $this->XF_KEYS[$XF_KEY] = $cs;
$this->XF[] = [$N, $cf, $A]; $this->XF[] = [$N, $A, $F, $FL, $C, $BG, $BR];
} }
} }
$row .= '<c r="' . $cname . '"' . ($ct ? ' t="' . $ct . '"' : '') . ($cs ? ' s="' . $cs . '"' : '') . '>' $row .= '<c r="' . $cname . '"' . ($ct ? ' t="' . $ct . '"' : '') . ($cs ? ' s="' . $cs . '"' : '') . '>'
. ($cf ? '<f>' . $cf . '</f>' : '')
. ($ct === 'inlineStr' ? '<is><t>' . $cv . '</t></is>' : '<v>' . $cv . '</v>') . "</c>\r\n"; . ($ct === 'inlineStr' ? '<is><t>' . $cv . '</t></is>' : '<v>' . $cv . '</v>') . "</c>\r\n";
} }
$ROWS[] = $row . "</row>\r\n"; $ROWS[] = '<row r="' . $CUR_ROW . '"' . ($RH ? ' customHeight="1" ht="' . $RH . '"' : '') . '>' . $row . "</row>";
} }
foreach ($COL as $k => $max) { foreach ($COL as $k => $max) {
$COLS[] = '<col min="'.$k.'" max="'.$k.'" width="'.min( $max+1, 60).'" />'; $w = isset($this->sheets[$idx]['colwidth'][$k]) ? $this->sheets[$idx]['colwidth'][$k] : min($max + 1, 60);
$COLS[] = '<col min="' . $k . '" max="' . $k . '" width="' . $w . '" customWidth="1" />';
} }
$COLS[] = '</cols>'; $COLS[] = '</cols>';
$REF = 'A1:'.$this->num2name(count($COLS)) . $CUR_ROW; $REF = 'A1:' . $this->num2name(count($COL)) . $CUR_ROW;
} else { } else {
$ROWS[] = '<row r="1"><c r="A1" t="s"><v>0</v></c></row>'; $ROWS[] = '<row r="1"><c r="A1" t="s"><v>0</v></c></row>';
$REF = 'A1:A1'; $REF = 'A1:A1';
} }
$AUTOFILTER = '';
if ($this->sheets[$idx]['autofilter']) {
$AUTOFILTER = '<autoFilter ref="' . $this->sheets[$idx]['autofilter'] . '" />';
}
$MERGECELLS = [];
if (count($this->sheets[$idx]['mergecells'])) {
$MERGECELLS[] = '';
$MERGECELLS[] = '<mergeCells count="' . count($this->sheets[$idx]['mergecells']) . '">';
foreach ($this->sheets[$idx]['mergecells'] as $m) {
$MERGECELLS[] = '<mergeCell ref="' . $m . '"/>';
}
$MERGECELLS[] = '</mergeCells>';
}
$HYPERLINKS = []; $HYPERLINKS = [];
if (count($this->sheets[$idx]['hyperlinks'])) { if (count($this->sheets[$idx]['hyperlinks'])) {
$HYPERLINKS[] = '<hyperlinks>'; $HYPERLINKS[] = '<hyperlinks>';
foreach ($this->sheets[$idx]['hyperlinks'] as $h) { 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[] = '<hyperlink ref="' . $h['R'] . '"' . ($h['ID'] ? ' r:id="' . $h['ID'] . '"' : '') . ' location="' . $this->esc($h['L']) . '" display="' . $this->esc($h['H'] . ($h['L'] ? ' - ' . $h['L'] : '')) . '" />';
} }
$HYPERLINKS[] = '</hyperlinks>'; $HYPERLINKS[] = '</hyperlinks>';
} }
//restore locale //restore locale
setlocale(LC_NUMERIC, $_loc); setlocale(LC_NUMERIC, $_loc);
return str_replace(['{REF}','{COLS}','{ROWS}','{HYPERLINKS}'], return str_replace(['{REF}', '{COLS}', '{ROWS}', '{AUTOFILTER}', '{MERGECELLS}', '{HYPERLINKS}'],
[ $REF, implode("\r\n", $COLS), implode("\r\n",$ROWS), implode("\r\n", $HYPERLINKS) ], [$REF,
implode("\r\n", $COLS),
implode("\r\n", $ROWS),
$AUTOFILTER,
implode("\r\n", $MERGECELLS),
implode("\r\n", $HYPERLINKS)
],
$template); $template);
} }
public function num2name($num) { public function num2name($num)
{
$numeric = ($num - 1) % 26; $numeric = ($num - 1) % 26;
$letter = chr(65 + $numeric); $letter = chr(65 + $numeric);
$num2 = (int)(($num - 1) / 26); $num2 = (int)(($num - 1) / 26);
@ -624,16 +925,20 @@ class SimpleXLSXGen {
return $letter; return $letter;
} }
public 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; $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
if ( $year === 0 ) { if ((int)$year === 0) {
return $excelTime; return $excelTime;
} }
// self::CALENDAR_WINDOWS_1900 // self::CALENDAR_WINDOWS_1900
$excel1900isLeapYear = True; $excel1900isLeapYear = True;
if (((int)$year === 1900) && ($month <= 2)) { $excel1900isLeapYear = False; } if (($year === 1900) && ($month <= 2)) {
$excel1900isLeapYear = False;
}
$myExcelBaseDate = 2415020; $myExcelBaseDate = 2415020;
// Julian base date Adjustment // Julian base date Adjustment
@ -643,22 +948,68 @@ class SimpleXLSXGen {
$month += 9; $month += 9;
--$year; --$year;
} }
// Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
$century = substr($year, 0, 2); $century = substr($year, 0, 2);
$decade = substr($year, 2, 2); $decade = substr($year, 2, 2);
// Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
$excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myExcelBaseDate + $excel1900isLeapYear; $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myExcelBaseDate + $excel1900isLeapYear;
return (float)$excelDate + $excelTime; return (float)$excelDate + $excelTime;
} }
public function setDefaultFont( $name ) {
public function setDefaultFont($name)
{
$this->defaultFont = $name; $this->defaultFont = $name;
return $this; return $this;
} }
public function setDefaultFontSize( $size ) {
public function setDefaultFontSize($size)
{
$this->defaultFontSize = $size; $this->defaultFontSize = $size;
return $this; return $this;
} }
public function esc( $str ) {
return str_replace( ['&', '<', '>', "\x03"], ['&amp;', '&lt;', '&gt;', ''], $str ); public function autoFilter($range)
{
$this->sheets[$this->curSheet]['autofilter'] = $range;
return $this;
} }
public function mergeCells($range)
{
$this->sheets[$this->curSheet]['mergecells'][] = $range;
return $this;
}
public function setColWidth($col, $width)
{
$this->sheets[$this->curSheet]['colwidth'][$col] = $width;
return $this;
}
public function esc($str)
{
// XML UTF-8: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
// but we use fast version
return str_replace(['&', '<', '>', "\x00", "\x03", "\x0B"], ['&amp;', '&lt;', '&gt;', '', '', ''], $str);
}
public function getNumFmtId($code)
{
if (isset($this->NF[$code])) { // id?
return (int)$code;
}
if (isset($this->NF_KEYS[$code])) {
return $this->NF_KEYS[$code];
}
$id = 197 + count($this->NF); // custom
$this->NF[$id] = $code;
$this->NF_KEYS[$code] = $id;
return $id;
}
public static function raw($value)
{
return "\0" . (string)$value;
}
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 52 KiB