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

9 Commits

Author SHA1 Message Date
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
4 changed files with 119 additions and 10 deletions

View File

@ -1,4 +1,19 @@
# Changelog
## 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>`

View File

@ -74,11 +74,13 @@ $data = [
['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</center>', null],
['<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 )
->setDefaultFont( 'Courier New' )
->setDefaultFontSize( 14 )
->setColWidth(1, 35) // 1 - num column, 35 - size in chars
->mergeCells('A20:B20')
->saveAs('styles_and_tags.xlsx');
```
@ -102,6 +104,70 @@ $xlsx->addSheet( $books, 'Catalog 2021' );
$xlsx->addSheet( $books2, 'Stephen King catalog');
$xlsx->downloadAs('books_2021.xlsx');
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

View File

@ -50,11 +50,12 @@ class SimpleXLSXGen {
const A_TOP = 8;
const A_MIDDLE = 16;
const A_BOTTOM = 32;
const A_WRAPTEXT = 64;
public function __construct() {
$this->curSheet = -1;
$this->defaultFont = 'Calibri';
$this->sheets = [ ['name' => 'Sheet1', 'rows' => [], 'hyperlinks' => [], 'mergecells' => [] ] ];
$this->sheets = [ ['name' => 'Sheet1', 'rows' => [], 'hyperlinks' => [], 'mergecells' => [], 'colwidth' => [], 'autofilter' => '' ] ];
$this->SI = []; // sharedStrings index
$this->SI_KEYS = []; // & keys
$this->XF = [ // styles
@ -89,7 +90,7 @@ class SimpleXLSXGen {
'xl/worksheets/sheet1.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<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>{MERGECELLS}{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"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{HYPERLINKS}</Relationships>',
'xl/sharedStrings.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
@ -156,7 +157,7 @@ class SimpleXLSXGen {
}
}
$this->sheets[$this->curSheet] = ['name' => $name, 'hyperlinks' => [], 'mergecells' => []];
$this->sheets[$this->curSheet] = ['name' => $name, 'hyperlinks' => [], 'mergecells' => [], 'colwidth' => [], 'autofilter' => '' ];
if ( isset( $rows[0] ) && is_array($rows[0]) ) {
$this->sheets[$this->curSheet]['rows'] = $rows;
@ -354,7 +355,8 @@ class SimpleXLSXGen {
.($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_BOTTOM ? ' vertical="bottom"' : '')
.($xf[1] & self::A_WRAPTEXT ? ' wrapText="1"' : '');
$XF[] = '<xf numFmtId="'.$xf[0].'" fontId="'.$F_ID.'" fillId="'.$FL_ID.'" borderId="0" xfId="0"'
.($xf[0] > 0 ? ' applyNumberFormat="1"' : '')
@ -557,6 +559,9 @@ class SimpleXLSXGen {
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 ) ) {
$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] : ''];
@ -601,7 +606,7 @@ class SimpleXLSXGen {
$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;
$A += ($A & (self::A_LEFT | self::A_CENTER)) ? 0 : 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] : ''];
@ -615,7 +620,7 @@ class SimpleXLSXGen {
$N = 0;
}
}
if ( !$cv) {
if ( $cv === null ) {
$v = $this->esc( $v );
@ -682,7 +687,8 @@ class SimpleXLSXGen {
$ROWS[] = '<row r="'.$CUR_ROW.'"'.($RH ? ' customHeight="1" ht="'.$RH.'"' : '').'>'.$row . "</row>";
}
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.'" />';
}
$COLS[] = '</cols>';
$REF = 'A1:'.$this->num2name(count($COL)) . $CUR_ROW;
@ -691,6 +697,11 @@ class SimpleXLSXGen {
$REF = 'A1:A1';
}
$AUTOFILTER = '';
if ($this->sheets[$idx]['autofilter']) {
$AUTOFILTER = '<autoFilter ref="'.$this->sheets[$idx]['autofilter'].'" />';
}
$MERGECELLS = [];
if ( count($this->sheets[$idx]['mergecells']) ) {
$MERGECELLS[] = '';
@ -709,11 +720,18 @@ class SimpleXLSXGen {
}
$HYPERLINKS[] = '</hyperlinks>';
}
//restore locale
setlocale(LC_NUMERIC, $_loc);
return str_replace(['{REF}','{COLS}','{ROWS}','{MERGECELLS}','{HYPERLINKS}'],
[ $REF, implode("\r\n", $COLS), implode("\r\n",$ROWS), implode("\r\n", $MERGECELLS), implode("\r\n", $HYPERLINKS) ],
return str_replace(['{REF}','{COLS}','{ROWS}','{AUTOFILTER}','{MERGECELLS}','{HYPERLINKS}'],
[ $REF,
implode("\r\n", $COLS),
implode("\r\n",$ROWS),
$AUTOFILTER,
implode("\r\n", $MERGECELLS),
implode("\r\n", $HYPERLINKS)
],
$template );
}
@ -762,10 +780,20 @@ class SimpleXLSXGen {
$this->defaultFontSize = $size;
return $this;
}
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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 141 KiB

After

Width:  |  Height:  |  Size: 40 KiB