diff --git a/.gitignore b/.gitignore
index 2f82d3b..9b777f5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,5 @@
vendor*
/books.fw.png
/datatypes.fw.png
+/styles.fw.png
+/styles.png
diff --git a/README.md b/README.md
index e4c422f..cabef9b 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# SimpleXLSXGen class 0.9.25 (Official)
+# SimpleXLSXGen class 1.0.10 (Official)
[](https://www.patreon.com/shuchkin) [](https://github.com/shuchkin/simplexlsxgen/blob/master/license.md) [](https://github.com/shuchkin/simplexlsxgen/stargazers) [](https://github.com/shuchkin/simplexlsxgen/network) [](https://github.com/shuchkin/simplexlsxgen/issues)
Export data to Excel XLSX file. PHP XLSX generator. No external tools and libraries.
@@ -42,9 +42,11 @@ $data = [
['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', 'SimpleXLSXGen'],
['RAW string', "\0".'2020-10-04 16:02:00']
];
-SimpleXLSXGen::fromArray( $data )->saveAs('datatypes.xlsx');
+SimpleXLSXGen::fromArray( $data )->saveAs('datatypes.xlsx'); // or ->downloadAs('datatypes.xlsx');
```
![XLSX screenshot](datatypes.png)
### Fluid examples
@@ -60,6 +62,28 @@ $xlsx->addSheet( $books, 'Catalog 2021' );
$xlsx->addSheet( $books2, 'Stephen King catalog');
$xlsx->downloadAs('books_2021.xlsx');
```
+### Formatting
+```php
+$data = [
+ ['Normal', '12345.67'],
+ ['Bold', '12345.67'],
+ ['Italic', '12345.67'],
+ ['Underline', '12345.67'],
+ ['Strike', '12345.67'],
+ ['Bold + Italic', '12345.67'],
+ ['Hyperlink', 'https://github.com/shuchkin/simplexlsxgen'],
+ ['Italic + Hyperlink + Anchor', 'SimpleXLSXGen'],
+ ['Left', '12345.67'],
+ ['Center', '
12345.67'],
+ ['Right', 'Right Text'],
+ ['Center + Bold', 'Name']
+];
+SimpleXLSXGen::fromArray( $data )
+ ->setDefaultFont( 'Courier New' )
+ ->setDefaultFontSize( 14 )
+ ->saveAs('styles_and_tags.xlsx');
+```
+![XLSX screenshot](styles.png)
### Debug
```php
ini_set('error_reporting', E_ALL );
@@ -73,6 +97,7 @@ SimpleXLSXGen::fromArray( $data )->saveAs('debug.xlsx');
## History
+v1.0.10 (2021-05-03) + Hyperlinks, + Minimal formatting
v0.9.25 (2021-02-26) Added PHP Datetime object values in a cells
v0.9.24 (2021-02-26) * Percent
v0.9.23 (2021-01-25) Fix local floats in XML
diff --git a/datatypes.png b/datatypes.png
index 89a943f..9dc3dba 100644
Binary files a/datatypes.png and b/datatypes.png differ
diff --git a/src/SimpleXLSXGen.php b/src/SimpleXLSXGen.php
index 48e8ac2..c223ae0 100644
--- a/src/SimpleXLSXGen.php
+++ b/src/SimpleXLSXGen.php
@@ -8,27 +8,45 @@
class SimpleXLSXGen {
public $curSheet;
+ protected $defaultFont;
+ protected $defaultFontSize;
protected $sheets;
protected $template;
- protected $SI, $SI_KEYS;
+ 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->curSheet = -1;
- $this->sheets = [ ['name' => 'Sheet1', 'rows' => [] ] ];
+ $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' => '
-
-
-
-
-
-{SHEETS}
-
-
-
-',
'_rels/.rels' => '
@@ -51,33 +69,42 @@ class SimpleXLSXGen {
{SHEETS}',
'xl/worksheets/sheet1.xml' => '
-{COLS}{ROWS}',
+{COLS}{ROWS}{HYPERLINKS}',
+ 'xl/worksheets/_rels/sheet1.xml.rels' => '
+{HYPERLINKS}',
'xl/sharedStrings.xml' => '
{STRINGS}',
'xl/styles.xml' => '
-
+{FONTS}
-
-
-
-
-
-
-
-
-
-
-
+{XF}
+
+
+
',
'xl/workbook.xml' => '
{SHEETS}
-'
+',
+ '[Content_Types].xml' => '
+
+
+
+
+
+
+
+
+{TYPES}
+',
];
+
//
// 0100
1200
// Простой шаблонБудем делать генератор
@@ -90,7 +117,7 @@ class SimpleXLSXGen {
public function addSheet( array $rows, $name = null ) {
$this->curSheet++;
- $this->sheets[$this->curSheet] = ['name' => $name ?: 'Sheet'.($this->curSheet+1)];
+ $this->sheets[$this->curSheet] = ['name' => $name ?: 'Sheet'.($this->curSheet+1), 'hyperlinks' => []];
if ( is_array( $rows ) && isset( $rows[0] ) && is_array($rows[0]) ) {
$this->sheets[$this->curSheet]['rows'] = $rows;
@@ -177,17 +204,7 @@ class SimpleXLSXGen {
$cnt_sheets = count( $this->sheets );
foreach ($this->template as $cfilename => $template ) {
- if ( $cfilename === '[Content_Types].xml' ) {
- $s = '';
- for ( $i = 0; $i < $cnt_sheets; $i++) {
- $s .= '';
- }
- $template = str_replace('{SHEETS}', $s, $template);
- $this->_writeEntry($fh, $cdrec, $cfilename, $template);
- $entries++;
- }
- elseif ( $cfilename === 'xl/_rels/workbook.xml.rels' ) {
+ if ( $cfilename === 'xl/_rels/workbook.xml.rels' ) {
$s = '';
for ( $i = 0; $i < $cnt_sheets; $i++) {
$s .= '_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
- }
- elseif ( $cfilename === 'xl/workbook.xml' ) {
+ } elseif ( $cfilename === 'xl/workbook.xml' ) {
$s = '';
foreach ( $this->sheets as $k => $v ) {
$s .= '';
@@ -228,8 +244,61 @@ class SimpleXLSXGen {
$entries++;
}
$xml = null;
- }
- else {
+ } elseif ( $cfilename === 'xl/worksheets/_rels/sheet1.xml.rels' ) {
+ $RH = [];
+ foreach ( $this->sheets as $k => $v ) {
+ if ( count($v['hyperlinks'])) {
+ $filename = 'xl/worksheets/_rels/sheet' . ( $k + 1 ) . '.xml.rels';
+ foreach ( $v['hyperlinks'] as $h ) {
+ $RH[] = '';
+ }
+ $xml = str_replace( '{HYPERLINKS}', implode( "\r\n", $RH ), $template );
+ $this->_writeEntry( $fh, $cdrec, $filename, $xml );
+ $entries++;
+ }
+ }
+ $xml = null;
+
+ } elseif ( $cfilename === '[Content_Types].xml' ) {
+ $TYPES = [''];
+ foreach ( $this->sheets as $k => $v) {
+ $TYPES[] = '';
+ if (count( $v['hyperlinks'])) {
+ $TYPES[] = '';
+ }
+ }
+ $template = str_replace('{TYPES}', implode("\r\n", $TYPES), $template);
+ $this->_writeEntry($fh, $cdrec, $cfilename, $template);
+ $entries++;
+ } elseif ( $cfilename === 'xl/styles.xml' ) {
+ $FONTS = [''];
+ foreach ( $this->F as $f ) {
+ $FONTS[] = ''
+ . ( $this->defaultFontSize ? '' : '' )
+ .( $f & self::F_BOLD ? '' : '')
+ .( $f & self::F_ITALIC ? '' : '')
+ .( $f & self::F_UNDERLINE ? '' : '')
+ .( $f & self::F_STRIKE ? '' : '')
+ .( $f & self::F_HYPERLINK ? '' : '')
+ .'';
+ }
+ $FONTS[] = '';
+ $XF = [''];
+ foreach( $this->XF as $xf ) {
+ $align = ($xf[2] === self::A_LEFT ? ' applyAlignment="1">' : '')
+ .($xf[2] === self::A_RIGHT ? ' applyAlignment="1">' : '')
+ .($xf[2] === self::A_CENTER ? ' applyAlignment="1">' : '');
+ $XF[] = ' 0 ? ' applyNumberFormat="1"' : '')
+ .($align ? $align . '' : '/>');
+
+ }
+ $XF[] = '';
+ $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++;
}
@@ -337,6 +406,7 @@ class SimpleXLSXGen {
$COLS = [];
$ROWS = [];
if ( count($this->sheets[$idx]['rows']) ) {
+ $COLS[] = '';
$CUR_ROW = 0;
$COL = [];
foreach( $this->sheets[$idx]['rows'] as $r ) {
@@ -354,60 +424,106 @@ class SimpleXLSXGen {
$cname = $this->num2name($CUR_COL) . $CUR_ROW;
- $ct = $cs = null;
+ $ct = $cv = null;
+ $N = $F = $A = 0;
if ( is_string($v) ) {
- $vl = mb_strlen( $v );
-
- if ( $v === '0' || preg_match( '/^[-+]?[1-9]\d{0,14}$/', $v ) ) { // Integer as General
- $cv = ltrim( $v, '+' );
- if ( $vl > 10 ) {
- $cs = 1; // [1] 0
- }
- } elseif ( preg_match('/^[-+]?(0|[1-9]\d*)\.\d+$/', $v ) ) {
- $cv = ltrim($v,'+');
- } elseif ( preg_match('/^([-+]?\d+)%$/', $v, $m) ) {
- $cv = round( $m[1] / 100, 2);
- $cs = 2; // [9] 0%
- } elseif ( preg_match('/^([-+]\d+\.\d+)%$/', $v, $m) ) {
- $cv = round( $m[1] / 100, 4 );
- $cs = 3; // [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 = 4; // [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]);
- $cs = 4; // [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 = 5; // [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 = 6; // [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] );
- $cs = 6; // [22] m/d/yy h:mm
- } elseif ( mb_strlen( $v ) > 160 ) {
- $ct = 'inlineStr';
- $cv = str_replace(['&','<','>',"\x03"],['&','<','>',''], $v);
+ if ( $v[0] === "\0" ) { // RAW value as string
+ $v = substr($v,1);
+ $vl = mb_strlen( $v );
} else {
- if ( preg_match('/^[0-9+-.]+$/', $v ) ) { // Long ?
- $cs = 7; // Align Right
- }
- $v = ltrim($v,"\0"); // disabled type detection
- $ct = 's'; // shared string
- $v = str_replace(['&','<','>',"\x03"],['&','<','>',''], $v);
- $cv = false;
- $skey = '~'.$v;
- if ( isset($this->SI_KEYS[ $skey ]) ) {
- $cv = $this->SI_KEYS[ $skey ];
+ if ( strpos( $v, '<' ) !== false ) { // tags?
+ if ( strpos( $v, '' ) !== false ) {
+ $F += self::F_BOLD;
+ }
+ if ( strpos( $v, '' ) !== false ) {
+ $F += self::F_ITALIC;
+ }
+ if ( strpos( $v, '' ) !== false ) {
+ $F += self::F_UNDERLINE;
+ }
+ if ( strpos( $v, '' ) !== false ) {
+ $F += self::F_STRIKE;
+ }
+ if ( strpos( $v, '' ) !== false ) {
+ $A += self::A_LEFT;
+ }
+ if ( strpos( $v, '' ) !== false ) {
+ $A += self::A_CENTER;
+ }
+ if ( strpos( $v, '' ) !== false ) {
+ $A += self::A_RIGHT;
+ }
+ if ( preg_match( '/(.*?)<\/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
+ }
+ $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\-\.]*)/i", $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) {
- if ( $cv === false ) {
- $this->SI[] = $v;
- $cv = count( $this->SI ) - 1;
- $this->SI_KEYS[$skey] = $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 ) ) {
@@ -419,13 +535,34 @@ class SimpleXLSXGen {
} 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') );
- $cs = 6; // [22] m/d/yy h:mm
+ $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 .= ''
.($ct === 'inlineStr' ? ''.$cv.'' : '' . $cv . '')."\r\n";
}
@@ -434,17 +571,25 @@ class SimpleXLSXGen {
foreach ( $COL as $k => $max ) {
$COLS[] = '';
}
+ $COLS[] = '';
$REF = 'A1:'.$this->num2name(count($COLS)) . $CUR_ROW;
} else {
- $COLS[] = '';
$ROWS[] = '0
';
$REF = 'A1:A1';
}
+ $HYPERLINKS = [];
+ if ( count( $this->sheets[$idx]['hyperlinks']) ) {
+ $HYPERLINKS[] = '';
+ foreach ( $this->sheets[$idx]['hyperlinks'] as $h ) {
+ $HYPERLINKS[] = '';
+ }
+ $HYPERLINKS[] = '';
+ }
//restore locale
setlocale(LC_NUMERIC, $_loc);
- return str_replace(['{REF}','{COLS}','{ROWS}'],
- [ $REF, implode("\r\n", $COLS), implode("\r\n",$ROWS) ],
+ return str_replace(['{REF}','{COLS}','{ROWS}','{HYPERLINKS}'],
+ [ $REF, implode("\r\n", $COLS), implode("\r\n",$ROWS), implode("\r\n", $HYPERLINKS) ],
$template );
}
@@ -484,4 +629,15 @@ class SimpleXLSXGen {
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"], ['&', '<', '>', ''], $str );
+ }
}