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

1016 lines
46 KiB
PHP
Raw Normal View History

2022-04-24 11:59:15 +03:00
<?php /** @noinspection ReturnTypeCanBeDeclaredInspection */
/** @noinspection PhpMissingReturnTypeInspection */
/** @noinspection NullCoalescingOperatorCanBeUsedInspection */
/** @noinspection PhpIssetCanBeReplacedWithCoalesceInspection */
2022-02-05 15:32:10 +03:00
namespace Shuchkin;
2020-05-19 23:46:52 +03:00
/**
* Class SimpleXLSXGen
* Export data to MS Excel. PHP XLSX generator
* Author: sergey.shuchkin@gmail.com
*/
2022-12-14 18:30:23 +03:00
class SimpleXLSXGen
{
2020-05-19 23:46:52 +03:00
2022-02-05 15:32:10 +03:00
public $curSheet;
protected $defaultFont;
protected $defaultFontSize;
protected $sheets;
protected $template;
2022-12-14 18:30:23 +03:00
protected $NF; // numFmts
protected $NF_KEYS;
protected $XF; // cellXfs
protected $XF_KEYS;
protected $BR_STYLE;
protected $SI; // shared strings
protected $SI_KEYS;
protected $extLinkId;
2022-02-05 15:32:10 +03:00
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
2022-12-14 18:30:23 +03:00
const N_RUB = 164;
const N_DOLLAR = 165;
const N_EURO = 166;
2022-02-05 15:32:10 +03:00
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;
2022-04-24 11:59:15 +03:00
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
2022-12-14 18:30:23 +03:00
const FL_LIGHT_GRAY = 8; // lightGray
2022-04-24 11:59:15 +03:00
const FL_GRAY_125 = 16; // gray125
const FL_COLOR = 32;
2022-02-05 15:32:10 +03:00
const A_DEFAULT = 0;
const A_LEFT = 1;
const A_RIGHT = 2;
2022-05-17 09:03:35 +03:00
const A_CENTER = 4;
const A_TOP = 8;
const A_MIDDLE = 16;
const A_BOTTOM = 32;
2022-07-05 08:19:42 +03:00
const A_WRAPTEXT = 64;
2022-12-14 18:30:23 +03:00
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()
{
2022-02-05 15:32:10 +03:00
$this->curSheet = -1;
$this->defaultFont = 'Calibri';
2022-12-14 18:30:23 +03:00
$this->sheets = [['name' => 'Sheet1', 'rows' => [], 'hyperlinks' => [], 'mergecells' => [], 'colwidth' => [], 'autofilter' => '']];
$this->extLinkId = 0;
$this->SI = []; // sharedStrings index
2022-02-05 15:32:10 +03:00
$this->SI_KEYS = []; // & keys
2022-12-14 18:30:23 +03:00
// https://c-rex.net/projects/samples/ooxml/e1/Part4/OOXML_P4_DOCX_numFmts_topic_ID0E6KK6.html
$this->NF = [
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
2022-04-24 11:59:15 +03:00
];
2022-12-14 18:30:23 +03:00
$this->XF_KEYS[implode('-', $this->XF[0])] = 0; // & keys
$this->XF_KEYS[implode('-', $this->XF[1])] = 1;
2022-02-05 15:32:10 +03:00
$this->template = [
'_rels/.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2020-05-19 23:46:52 +03:00
<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"/>
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>
</Relationships>',
2022-02-05 15:32:10 +03:00
'docProps/app.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2020-05-19 23:46:52 +03:00
<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">
<TotalTime>0</TotalTime>
2022-12-14 18:30:23 +03:00
<Application>' . __CLASS__ . '</Application></Properties>',
2022-02-05 15:32:10 +03:00
'docProps/core.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2020-05-19 23:46:52 +03:00
<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<dcterms:created xsi:type="dcterms:W3CDTF">{DATE}</dcterms:created>
<dc:language>en-US</dc:language>
<dcterms:modified xsi:type="dcterms:W3CDTF">{DATE}</dcterms:modified>
<cp:revision>1</cp:revision>
</cp:coreProperties>',
2022-02-05 15:32:10 +03:00
'xl/_rels/workbook.xml.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2020-05-19 23:46:52 +03:00
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
{SHEETS}',
2022-02-05 15:32:10 +03:00
'xl/worksheets/sheet1.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2021-05-03 00:08:41 +03:00
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
2022-02-05 15:32:10 +03:00
xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
2022-08-12 15:57:41 +03:00
><dimension ref="{REF}"/>{COLS}<sheetData>{ROWS}</sheetData>{AUTOFILTER}{MERGECELLS}{HYPERLINKS}</worksheet>',
2022-02-05 15:32:10 +03:00
'xl/worksheets/_rels/sheet1.xml.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2021-05-03 00:08:41 +03:00
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{HYPERLINKS}</Relationships>',
2022-02-05 15:32:10 +03:00
'xl/sharedStrings.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2020-05-19 23:46:52 +03:00
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="{CNT}" uniqueCount="{CNT}">{STRINGS}</sst>',
2022-02-05 15:32:10 +03:00
'xl/styles.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2020-05-19 23:46:52 +03:00
<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
2022-12-14 18:30:23 +03:00
{NUMFMTS}
2021-05-03 00:08:41 +03:00
{FONTS}
{FILLS}
2022-12-14 18:30:23 +03:00
{BORDERS}
2020-05-19 23:46:52 +03:00
<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" /></cellStyleXfs>
2021-05-03 00:08:41 +03:00
{XF}
<cellStyles count="1">
2022-02-05 15:32:10 +03:00
<cellStyle name="Normal" xfId="0" builtinId="0"/>
2021-05-03 00:08:41 +03:00
</cellStyles>
2020-05-19 23:46:52 +03:00
</styleSheet>',
2022-02-05 15:32:10 +03:00
'xl/workbook.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2020-05-19 23:46:52 +03:00
<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
2022-12-14 18:30:23 +03:00
<fileVersion appName="' . __CLASS__ . '"/><sheets>
{SHEETS}
2021-05-03 00:08:41 +03:00
</sheets></workbook>',
2022-02-05 15:32:10 +03:00
'[Content_Types].xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2021-05-03 00:08:41 +03:00
<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>',
2022-02-05 15:32:10 +03:00
];
2021-05-03 00:08:41 +03:00
2022-02-05 15:32:10 +03:00
// <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>
}
2022-12-14 18:30:23 +03:00
public static function fromArray(array $rows, $sheetName = null)
{
return (new static())->addSheet($rows, $sheetName);
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
public function addSheet(array $rows, $name = null)
{
2022-02-05 15:32:10 +03:00
$this->curSheet++;
2022-12-14 18:30:23 +03:00
if ($name === null) { // autogenerated sheet names
$name = 'Sheet' . ($this->curSheet + 1);
2022-02-05 15:32:10 +03:00
} else {
2022-02-12 00:04:46 +03:00
$name = mb_substr($name, 0, 31);
2022-02-05 15:32:10 +03:00
$names = [];
2022-12-14 18:30:23 +03:00
foreach ($this->sheets as $sh) {
$names[mb_strtoupper($sh['name'])] = 1;
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
for ($i = 0; $i < 100; $i++) {
$postfix = ' (' . $i . ')';
2022-02-12 00:25:59 +03:00
$new_name = ($i === 0) ? $name : $name . $postfix;
if (mb_strlen($new_name) > 31) {
2022-12-14 18:30:23 +03:00
$new_name = mb_substr($name, 0, 31 - mb_strlen($postfix)) . $postfix;
2022-02-12 00:25:59 +03:00
}
2022-12-14 18:30:23 +03:00
$NEW_NAME = mb_strtoupper($new_name);
if (!isset($names[$NEW_NAME])) {
2022-02-05 15:32:10 +03:00
$name = $new_name;
break;
}
}
}
2022-12-14 18:30:23 +03:00
$this->sheets[$this->curSheet] = ['name' => $name, 'hyperlinks' => [], 'mergecells' => [], 'colwidth' => [], 'autofilter' => ''];
2022-02-05 15:32:10 +03:00
2022-12-14 18:30:23 +03:00
if (isset($rows[0]) && is_array($rows[0])) {
2022-02-05 15:32:10 +03:00
$this->sheets[$this->curSheet]['rows'] = $rows;
} else {
$this->sheets[$this->curSheet]['rows'] = [];
}
return $this;
}
2022-12-14 18:30:23 +03:00
public function __toString()
{
$fh = fopen('php://memory', 'wb');
if (!$fh) {
2022-02-05 15:32:10 +03:00
return '';
}
2022-12-14 18:30:23 +03:00
if (!$this->_write($fh)) {
fclose($fh);
2022-02-05 15:32:10 +03:00
return '';
}
2022-12-14 18:30:23 +03:00
$size = ftell($fh);
fseek($fh, 0);
2022-02-05 15:32:10 +03:00
2022-12-14 18:30:23 +03:00
return (string)fread($fh, $size);
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
public function saveAs($filename)
{
$fh = fopen($filename, 'wb');
2022-02-05 15:32:10 +03:00
if (!$fh) {
return false;
}
2022-12-14 18:30:23 +03:00
if (!$this->_write($fh)) {
2022-02-05 15:32:10 +03:00
fclose($fh);
return false;
}
fclose($fh);
return true;
}
2022-12-14 18:30:23 +03:00
public function download()
{
return $this->downloadAs(gmdate('YmdHi') . '.xlsx');
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
public function downloadAs($filename)
{
$fh = fopen('php://memory', 'wb');
2022-02-05 15:32:10 +03:00
if (!$fh) {
return false;
}
2022-12-14 18:30:23 +03:00
if (!$this->_write($fh)) {
fclose($fh);
2022-02-05 15:32:10 +03:00
return false;
}
$size = ftell($fh);
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
2022-12-14 18:30:23 +03:00
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T', time()));
header('Content-Length: ' . $size);
2022-02-05 15:32:10 +03:00
2022-12-14 18:30:23 +03:00
while (ob_get_level()) {
2022-02-05 15:32:10 +03:00
ob_end_clean();
}
2022-12-14 18:30:23 +03:00
fseek($fh, 0);
fpassthru($fh);
2022-02-05 15:32:10 +03:00
fclose($fh);
return true;
}
2022-12-14 18:30:23 +03:00
protected function _write($fh)
{
2022-02-05 15:32:10 +03:00
2022-12-14 18:30:23 +03:00
$dirSignatureE = "\x50\x4b\x05\x06"; // end of central dir signature
$zipComments = 'Generated by ' . __CLASS__ . ' PHP class, thanks sergey.shuchkin@gmail.com';
2022-02-05 15:32:10 +03:00
if (!$fh) {
return false;
}
2022-12-14 18:30:23 +03:00
$cdrec = ''; // central directory content
$entries = 0; // number of zipped files
$cnt_sheets = count($this->sheets);
2022-02-05 15:32:10 +03:00
2022-12-14 18:30:23 +03:00
foreach ($this->template as $cfilename => $template) {
if ($cfilename === 'xl/_rels/workbook.xml.rels') {
2022-02-05 15:32:10 +03:00
$s = '';
2022-12-14 18:30:23 +03:00
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";
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
$s .= '<Relationship Id="rId' . ($i + 2) . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/></Relationships>';
2022-02-05 15:32:10 +03:00
$template = str_replace('{SHEETS}', $s, $template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
2022-12-14 18:30:23 +03:00
} elseif ($cfilename === 'xl/workbook.xml') {
2022-02-05 15:32:10 +03:00
$s = '';
2022-12-14 18:30:23 +03:00
foreach ($this->sheets as $k => $v) {
$s .= '<sheet name="' . $this->esc($v['name']) . '" sheetId="' . ($k + 1) . '" state="visible" r:id="rId' . ($k + 2) . '"/>';
2022-02-05 15:32:10 +03:00
}
$template = str_replace('{SHEETS}', $s, $template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
2022-12-14 18:30:23 +03:00
} elseif ($cfilename === 'docProps/core.xml') {
2022-02-05 15:32:10 +03:00
$template = str_replace('{DATE}', gmdate('Y-m-d\TH:i:s\Z'), $template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
2022-12-14 18:30:23 +03:00
} elseif ($cfilename === 'xl/sharedStrings.xml') {
2022-02-05 15:32:10 +03:00
if (!count($this->SI)) {
$this->SI[] = 'No Data';
}
$si_cnt = count($this->SI);
2022-12-14 18:30:23 +03:00
$si = '<si><t>' . implode("</t></si>\r\n<si><t>", $this->SI) . '</t></si>';
$template = str_replace(['{CNT}', '{STRINGS}'], [$si_cnt, $si], $template);
2022-02-05 15:32:10 +03:00
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
2022-12-14 18:30:23 +03:00
} elseif ($cfilename === 'xl/worksheets/sheet1.xml') {
foreach ($this->sheets as $k => $v) {
$filename = 'xl/worksheets/sheet' . ($k + 1) . '.xml';
2022-02-05 15:32:10 +03:00
$xml = $this->_sheetToXML($k, $template);
2022-12-14 18:30:23 +03:00
$this->_writeEntry($fh, $cdrec, $filename, $xml);
2022-02-05 15:32:10 +03:00
$entries++;
}
$xml = null;
2022-12-14 18:30:23 +03:00
} elseif ($cfilename === 'xl/worksheets/_rels/sheet1.xml.rels') {
foreach ($this->sheets as $k => $v) {
if ($this->extLinkId) {
2022-02-05 15:32:10 +03:00
$RH = [];
2022-12-14 18:30:23 +03:00
$filename = 'xl/worksheets/_rels/sheet' . ($k + 1) . '.xml.rels';
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"/>';
}
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
$xml = str_replace('{HYPERLINKS}', implode("\r\n", $RH), $template);
$this->_writeEntry($fh, $cdrec, $filename, $xml);
2022-02-05 15:32:10 +03:00
$entries++;
}
}
$xml = null;
2022-12-14 18:30:23 +03:00
} elseif ($cfilename === '[Content_Types].xml') {
2022-02-05 15:32:10 +03:00
$TYPES = ['<Override PartName="/_rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'];
2022-12-14 18:30:23 +03:00
foreach ($this->sheets as $k => $v) {
$TYPES[] = '<Override PartName="/xl/worksheets/sheet' . ($k + 1) .
'.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
if ($this->extLinkId) {
$TYPES[] = '<Override PartName="/xl/worksheets/_rels/sheet' . ($k + 1) . '.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
2022-02-05 15:32:10 +03:00
}
}
$template = str_replace('{TYPES}', implode("\r\n", $TYPES), $template);
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
2022-12-14 18:30:23 +03:00
} elseif ($cfilename === 'xl/styles.xml') {
$NF = $XF = $FONTS = $F_KEYS = $FILLS = $FL_KEYS = [];
$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
2022-04-24 11:59:15 +03:00
// fonts
2022-12-14 18:30:23 +03:00
$F_KEY = $xf[2] . '-' . $xf[4];
if (isset($F_KEYS[$F_KEY])) {
$F_ID = $F_KEYS[$F_KEY];
2022-04-24 11:59:15 +03:00
} else {
2022-12-14 18:30:23 +03:00
$F_ID = $F_KEYS[$F_KEY] = count($FONTS);
$FONTS[] = '<font><name val="' . $this->defaultFont . '"/><family val="2"/>'
. ($this->defaultFontSize ? '<sz val="' . $this->defaultFontSize . '"/>' : '')
. ($xf[2] & self::F_BOLD ? '<b/>' : '')
. ($xf[2] & self::F_ITALIC ? '<i/>' : '')
. ($xf[2] & self::F_UNDERLINE ? '<u/>' : '')
. ($xf[2] & self::F_STRIKE ? '<strike/>' : '')
. ($xf[2] & self::F_HYPERLINK ? '<u/>' : '')
. ($xf[2] & self::F_COLOR ? '<color rgb="' . $xf[4] . '"/>' : '')
. '</font>';
2022-04-24 11:59:15 +03:00
}
// fills
2022-12-14 18:30:23 +03:00
$FL_KEY = $xf[3] . '-' . $xf[5];
2022-04-24 11:59:15 +03:00
if (isset($FL_KEYS[$FL_KEY])) {
2022-12-14 18:30:23 +03:00
$FL_ID = $FL_KEYS[$FL_KEY];
2022-04-24 11:59:15 +03:00
} else {
2022-12-14 18:30:23 +03:00
$FL_ID = $FL_KEYS[$FL_KEY] = count($FILLS);
2022-04-24 11:59:15 +03:00
$FILLS[] = '<fill><patternFill patternType="'
2022-12-14 18:30:23 +03:00
. ($xf[3] === 0 ? 'none' : '')
. ($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>';
2022-04-24 11:59:15 +03:00
}
2022-05-17 09:03:35 +03:00
$align = ($xf[1] & self::A_LEFT ? ' horizontal="left"' : '')
2022-12-14 18:30:23 +03:00
. ($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 = '';
$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 {
$s = 'thin';
$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>' : '/>');
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
2022-04-24 11:59:15 +03:00
// wrap collections
2022-12-14 18:30:23 +03:00
array_unshift($NF, '<numFmts count="' . count($NF) . '">');
$NF[] = '</numFmts>';
array_unshift($XF, '<cellXfs count="' . count($XF) . '">');
2022-02-05 15:32:10 +03:00
$XF[] = '</cellXfs>';
2022-12-14 18:30:23 +03:00
array_unshift($FONTS, '<fonts count="' . count($FONTS) . '">');
2022-04-24 11:59:15 +03:00
$FONTS[] = '</fonts>';
2022-12-14 18:30:23 +03:00
array_unshift($FILLS, '<fills count="' . count($FILLS) . '">');
$FILLS[] = '</fills>';
2022-12-14 18:30:23 +03:00
array_unshift($BR, '<borders count="' . count($BR) . '">');
$BR[] = '</borders>';
2022-04-24 11:59:15 +03:00
2022-12-14 18:30:23 +03:00
$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);
2022-02-05 15:32:10 +03:00
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
} else {
$this->_writeEntry($fh, $cdrec, $cfilename, $template);
$entries++;
}
}
$before_cd = ftell($fh);
fwrite($fh, $cdrec);
// end of central dir
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', $entries)); // total # of entries "on this disk"
fwrite($fh, pack('v', $entries)); // total # of entries overall
2022-12-14 18:30:23 +03:00
fwrite($fh, pack('V', mb_strlen($cdrec, '8bit'))); // size of central dir
2022-02-05 15:32:10 +03:00
fwrite($fh, pack('V', $before_cd)); // offset to start of central dir
2022-12-14 18:30:23 +03:00
fwrite($fh, pack('v', mb_strlen($zipComments, '8bit'))); // .zip file comment length
2022-02-05 15:32:10 +03:00
fwrite($fh, $zipComments);
return true;
}
2022-12-14 18:30:23 +03:00
protected function _writeEntry($fh, &$cdrec, $cfilename, $data)
{
2022-02-05 15:32:10 +03:00
$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
2022-12-14 18:30:23 +03:00
if ($e['uncsize'] < 256) {
2022-02-05 15:32:10 +03:00
$e['comsize'] = $e['uncsize'];
$e['vneeded'] = 10;
$e['cmethod'] = 0;
$zdata = $data;
2022-12-14 18:30:23 +03:00
} else { // otherwise, compress it
2022-02-05 15:32:10 +03:00
$zdata = gzcompress($data);
2022-12-14 18:30:23 +03:00
$zdata = substr(substr($zdata, 0, -4), 2); // fix crc bug (thanks to Eric Mueller)
2022-02-05 15:32:10 +03:00
$e['comsize'] = mb_strlen($zdata, '8bit');
$e['vneeded'] = 10;
$e['cmethod'] = 8;
}
$e['bitflag'] = 0;
2022-12-14 18:30:23 +03:00
$e['crc_32'] = crc32($data);
2022-02-05 15:32:10 +03:00
// Convert date and time to DOS Format, and set then
2022-12-14 18:30:23 +03:00
$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);
2022-02-05 15:32:10 +03:00
# 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
2022-12-14 18:30:23 +03:00
$e['external_attributes'] = (substr($cfilename, -1) === '/' && !$zdata) ? 16 : 32; // Directory or file name
$e['comments'] = '';
2022-02-05 15:32:10 +03:00
$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
2022-12-14 18:30:23 +03:00
$cdrec .= pack('v', mb_strlen($cfilename, '8bit')); // file name length
2022-02-05 15:32:10 +03:00
$cdrec .= pack('v', 0); // extra field length
2022-12-14 18:30:23 +03:00
$cdrec .= pack('v', mb_strlen($e['comments'], '8bit')); // file comment length
2022-02-05 15:32:10 +03:00
$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'];
}
2022-12-14 18:30:23 +03:00
protected function _sheetToXML($idx, $template)
{
2022-02-05 15:32:10 +03:00
// locale floats fr_FR 1.234,56 -> 1234.56
$_loc = setlocale(LC_NUMERIC, 0);
2022-12-14 18:30:23 +03:00
setlocale(LC_NUMERIC, 'C');
2022-02-05 15:32:10 +03:00
$COLS = [];
$ROWS = [];
2022-12-14 18:30:23 +03:00
if (count($this->sheets[$idx]['rows'])) {
2022-02-05 15:32:10 +03:00
$COLS[] = '<cols>';
$CUR_ROW = 0;
$COL = [];
2022-12-14 18:30:23 +03:00
foreach ($this->sheets[$idx]['rows'] as $r) {
2022-02-05 15:32:10 +03:00
$CUR_ROW++;
2022-04-30 11:04:13 +03:00
$row = '';
2022-02-05 15:32:10 +03:00
$CUR_COL = 0;
2022-04-30 11:04:13 +03:00
$RH = 0; // row height
2022-12-14 18:30:23 +03:00
foreach ($r as $v) {
2022-02-05 15:32:10 +03:00
$CUR_COL++;
2022-12-14 18:30:23 +03:00
if (!isset($COL[$CUR_COL])) {
$COL[$CUR_COL] = 0;
2022-02-05 15:32:10 +03:00
}
2022-03-15 18:47:33 +03:00
$cname = $this->num2name($CUR_COL) . $CUR_ROW;
2022-12-14 18:30:23 +03:00
if ($v === null || $v === '') {
$row .= '<c r="' . $cname . '"/>';
2022-02-05 15:32:10 +03:00
continue;
}
2022-12-14 18:30:23 +03:00
$ct = $cv = $cf = null;
$N = $A = $F = $FL = $C = $BG = 0;
$BR = '';
2022-02-05 15:32:10 +03:00
2022-12-14 18:30:23 +03:00
if (is_string($v)) {
2022-02-05 15:32:10 +03:00
2022-12-14 20:47:14 +03:00
if ($v[0] === "\0") { // RAW value as string
2022-12-14 18:30:23 +03:00
$v = substr($v, 1);
$vl = mb_strlen($v);
2022-02-05 15:32:10 +03:00
} else {
2022-12-14 18:30:23 +03:00
if (strpos($v, '<') !== false) { // tags?
if (strpos($v, '<b>') !== false) {
2022-02-05 15:32:10 +03:00
$F += self::F_BOLD;
}
2022-12-14 18:30:23 +03:00
if (strpos($v, '<i>') !== false) {
2022-02-05 15:32:10 +03:00
$F += self::F_ITALIC;
}
2022-12-14 18:30:23 +03:00
if (strpos($v, '<u>') !== false) {
2022-02-05 15:32:10 +03:00
$F += self::F_UNDERLINE;
}
2022-12-14 18:30:23 +03:00
if (strpos($v, '<s>') !== false) {
2022-02-05 15:32:10 +03:00
$F += self::F_STRIKE;
}
2022-12-14 18:30:23 +03:00
if (preg_match('/<style([^>]+)>/', $v, $m)) {
2022-04-24 11:59:15 +03:00
2022-12-14 18:30:23 +03:00
if (preg_match('/ color="([^"]+)"/', $m[1], $m2)) {
2022-04-24 11:59:15 +03:00
$F += self::F_COLOR;
2022-12-14 18:30:23 +03:00
$c = ltrim($m2[1], '#');
$C = strlen($c) === 8 ? $c : ('FF' . $c);
2022-04-23 04:33:17 +03:00
}
2022-12-14 18:30:23 +03:00
if (preg_match('/ bgcolor="([^"]+)"/', $m[1], $m2)) {
2022-04-24 11:59:15 +03:00
$FL += self::FL_COLOR;
2022-12-14 18:30:23 +03:00
$c = ltrim($m2[1], '#');
$BG = strlen($c) === 8 ? $c : ('FF' . $c);
2022-04-23 04:33:17 +03:00
}
2022-12-14 18:30:23 +03:00
if (preg_match('/ height="([^"]+)"/', $m[1], $m2)) {
2022-04-30 11:04:13 +03:00
$RH = $m2[1];
}
2022-12-14 18:30:23 +03:00
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;
}
}
}
2022-12-14 18:30:23 +03:00
if (strpos($v, '<left>') !== false) {
2022-02-05 15:32:10 +03:00
$A += self::A_LEFT;
}
2022-12-14 18:30:23 +03:00
if (strpos($v, '<center>') !== false) {
2022-02-05 15:32:10 +03:00
$A += self::A_CENTER;
}
2022-12-14 18:30:23 +03:00
if (strpos($v, '<right>') !== false) {
2022-02-05 15:32:10 +03:00
$A += self::A_RIGHT;
}
2022-12-14 18:30:23 +03:00
if (strpos($v, '<top>') !== false) {
2022-05-17 09:03:35 +03:00
$A += self::A_TOP;
}
2022-12-14 18:30:23 +03:00
if (strpos($v, '<middle>') !== false) {
2022-05-17 09:03:35 +03:00
$A += self::A_MIDDLE;
}
2022-12-14 18:30:23 +03:00
if (strpos($v, '<bottom>') !== false) {
2022-05-17 09:03:35 +03:00
$A += self::A_BOTTOM;
}
2022-12-14 18:30:23 +03:00
if (strpos($v, '<wraptext>') !== false) {
2022-07-05 08:19:42 +03:00
$A += self::A_WRAPTEXT;
}
2022-12-14 18:30:23 +03:00
if (preg_match('/<a href="(https?:\/\/[^"]+)">(.*?)<\/a>/i', $v, $m)) {
$h = explode('#', $m[1]);
$this->extLinkId++;
$this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, 'R' => $cname, 'H' => $h[0], 'L' => isset($h[1]) ? $h[1] : ''];
2022-04-24 11:59:15 +03:00
$F += self::F_HYPERLINK; // Hyperlink
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
if (preg_match('/<a href="(mailto?:[^"]+)">(.*?)<\/a>/i', $v, $m)) {
$this->extLinkId++;
$this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, 'R' => $cname, 'H' => $m[1], 'L' => ''];
2022-04-24 11:59:15 +03:00
$F += self::F_HYPERLINK; // mailto hyperlink
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
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);
}
2022-02-05 15:32:10 +03:00
} // tags
2022-12-14 18:30:23 +03:00
$vl = mb_strlen($v);
if ($N) {
$cv = ltrim($v, '+');
} elseif ($v === '0' || preg_match('/^[-+]?[1-9]\d{0,14}$/', $v)) { // Integer as General
$cv = ltrim($v, '+');
if ($vl > 10) {
2022-02-05 15:32:10 +03:00
$N = self::N_INT; // [1] 0
}
2022-12-14 18:30:23 +03:00
} elseif (preg_match('/^[-+]?(0|[1-9]\d*)\.(\d+)$/', $v, $m)) {
$cv = ltrim($v, '+');
if (strlen($m[2]) < 3) {
2022-02-05 15:32:10 +03:00
$N = self::N_DEC;
}
2022-12-14 18:30:23 +03:00
} elseif (preg_match('/^(\$)?[-+]?[0-9\.]+( ₽| €)?$/u', $v, $m)) { // currency?
if ($m[1] === '$') {
$N = self::N_DOLLAR;
} elseif ($m[2] === ' ₽') {
$N = self::N_RUB;
} elseif ($m[2] === ' €') {
$N = self::N_EURO;
}
$cv = trim($v, ' +$₽€');
} elseif (preg_match('/^([-+]?\d+)%$/', $v, $m)) {
$cv = round($m[1] / 100, 2);
2022-02-05 15:32:10 +03:00
$N = self::N_PERCENT_INT; // [9] 0%
2022-12-14 18:30:23 +03:00
} elseif (preg_match('/^([-+]?\d+\.\d+)%$/', $v, $m)) {
$cv = round($m[1] / 100, 4);
2022-02-05 15:32:10 +03:00
$N = self::N_PRECENT_DEC; // [10] 0.00%
2022-12-14 18:30:23 +03:00
} elseif (preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d)$/', $v, $m)) {
$cv = $this->date2excel($m[1], $m[2], $m[3]);
2022-02-05 15:32:10 +03:00
$N = self::N_DATE; // [14] mm-dd-yy
2022-12-14 18:30:23 +03:00
} elseif (preg_match('/^(\d\d)\/(\d\d)\/(\d\d\d\d)$/', $v, $m)) {
$cv = $this->date2excel($m[3], $m[2], $m[1]);
2022-02-05 15:32:10 +03:00
$N = self::N_DATE; // [14] mm-dd-yy
2022-12-14 18:30:23 +03:00
} elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $v, $m)) {
$cv = $this->date2excel(0, 0, 0, $m[1], $m[2], $m[3]);
2022-02-05 15:32:10 +03:00
$N = self::N_TIME; // time
2022-12-14 18:30:23 +03:00
} 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 = ((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)) {
$cv = $this->date2excel($m[3], $m[2], $m[1], $m[4], $m[5], $m[6]);
2022-02-05 15:32:10 +03:00
$N = self::N_DATETIME; // [22] m/d/yy h:mm
2022-12-14 18:30:23 +03:00
} elseif (preg_match('/^[0-9+-.]+$/', $v)) { // Long ?
2022-06-01 09:54:28 +03:00
$A += ($A & (self::A_LEFT | self::A_CENTER)) ? 0 : self::A_RIGHT;
2022-12-14 18:30:23 +03:00
} elseif (preg_match('/^https?:\/\/\S+$/i', $v)) {
$h = explode('#', $v);
$this->extLinkId++;
$this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, 'R' => $cname, 'H' => $h[0], 'L' => isset($h[1]) ? $h[1] : ''];
2022-04-24 11:59:15 +03:00
$F += self::F_HYPERLINK; // Hyperlink
2022-12-14 18:30:23 +03:00
} elseif (preg_match("/^[a-zA-Z0-9_\.\-]+@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/", $v)) {
$this->extLinkId++;
$this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->extLinkId, 'R' => $cname, 'H' => 'mailto:' . $v, 'L' => ''];
2022-04-24 11:59:15 +03:00
$F += self::F_HYPERLINK; // Hyperlink
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
if (($N === self::N_DATE || $N === self::N_DATETIME) && $cv < 0) {
2022-01-31 23:50:32 +03:00
$cv = null;
$N = 0;
}
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
if ($cv === null) {
2022-02-05 15:32:10 +03:00
2022-12-14 18:30:23 +03:00
$v = $this->esc($v);
2022-02-05 15:32:10 +03:00
2022-12-14 18:30:23 +03:00
if ($cf) {
$ct = 'str';
$cv = $v;
} elseif (mb_strlen($v) > 160) {
2022-02-05 15:32:10 +03:00
$ct = 'inlineStr';
$cv = $v;
} else {
$ct = 's'; // shared string
$cv = false;
$skey = '~' . $v;
2022-12-14 18:30:23 +03:00
if (isset($this->SI_KEYS[$skey])) {
$cv = $this->SI_KEYS[$skey];
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
if ($cv === false) {
2022-02-05 15:32:10 +03:00
$this->SI[] = $v;
2022-12-14 18:30:23 +03:00
$cv = count($this->SI) - 1;
$this->SI_KEYS[$skey] = $cv;
2022-02-05 15:32:10 +03:00
}
}
}
2022-12-14 18:30:23 +03:00
} elseif (is_int($v)) {
$vl = mb_strlen((string)$v);
2022-02-05 15:32:10 +03:00
$cv = $v;
2022-12-14 18:30:23 +03:00
} elseif (is_float($v)) {
$vl = mb_strlen((string)$v);
2022-02-05 15:32:10 +03:00
$cv = $v;
2022-12-14 18:30:23 +03:00
} elseif ($v instanceof \DateTime) {
2022-02-05 15:32:10 +03:00
$vl = 16;
2022-03-15 18:47:33 +03:00
$cv = $this->date2excel($v->format('Y'), $v->format('m'), $v->format('d'), $v->format('H'), $v->format('i'), $v->format('s'));
2022-02-05 15:32:10 +03:00
$N = self::N_DATETIME; // [22] m/d/yy h:mm
} else {
continue;
}
2022-12-14 18:30:23 +03:00
$COL[$CUR_COL] = max($vl, $COL[$CUR_COL]);
2022-02-05 15:32:10 +03:00
$cs = 0;
2022-12-14 18:30:23 +03:00
if (($N + $A + $F + $FL > 0) || $BR !== '') {
2022-04-24 11:59:15 +03:00
2022-12-14 18:30:23 +03:00
if ($FL === self::FL_COLOR) {
2022-04-24 11:59:15 +03:00
$FL += self::FL_SOLID;
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
if (($F & self::F_HYPERLINK) && !($F & self::F_COLOR)) {
2022-04-24 11:59:15 +03:00
$F += self::F_COLOR;
$C = 'FF0563C1';
}
2022-04-24 11:59:15 +03:00
2022-12-14 18:30:23 +03:00
$XF_KEY = $N . '-' . $A . '-' . $F . '-' . $FL . '-' . $C . '-' . $BG . '-' . $BR;
2022-04-24 11:59:15 +03:00
// echo $cname .'='.$XF_KEY.PHP_EOL;
2022-12-14 18:30:23 +03:00
if (isset($this->XF_KEYS[$XF_KEY])) {
$cs = $this->XF_KEYS[$XF_KEY];
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
if ($cs === 0) {
$cs = count($this->XF);
$this->XF_KEYS[$XF_KEY] = $cs;
$this->XF[] = [$N, $A, $F, $FL, $C, $BG, $BR];
2022-02-05 15:32:10 +03:00
}
}
2022-03-15 18:47:33 +03:00
$row .= '<c r="' . $cname . '"' . ($ct ? ' t="' . $ct . '"' : '') . ($cs ? ' s="' . $cs . '"' : '') . '>'
2022-12-14 18:30:23 +03:00
. ($cf ? '<f>' . $cf . '</f>' : '')
. ($ct === 'inlineStr' ? '<is><t>' . $cv . '</t></is>' : '<v>' . $cv . '</v>') . "</c>\r\n";
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
$ROWS[] = '<row r="' . $CUR_ROW . '"' . ($RH ? ' customHeight="1" ht="' . $RH . '"' : '') . '>' . $row . "</row>";
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
foreach ($COL as $k => $max) {
$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" />';
2022-02-05 15:32:10 +03:00
}
$COLS[] = '</cols>';
2022-12-14 18:30:23 +03:00
$REF = 'A1:' . $this->num2name(count($COL)) . $CUR_ROW;
2022-02-05 15:32:10 +03:00
} else {
$ROWS[] = '<row r="1"><c r="A1" t="s"><v>0</v></c></row>';
$REF = 'A1:A1';
}
2022-03-15 18:47:33 +03:00
2022-08-12 15:57:41 +03:00
$AUTOFILTER = '';
if ($this->sheets[$idx]['autofilter']) {
2022-12-14 18:30:23 +03:00
$AUTOFILTER = '<autoFilter ref="' . $this->sheets[$idx]['autofilter'] . '" />';
2022-08-12 15:57:41 +03:00
}
2022-03-15 18:47:33 +03:00
$MERGECELLS = [];
2022-12-14 18:30:23 +03:00
if (count($this->sheets[$idx]['mergecells'])) {
2022-03-15 18:47:33 +03:00
$MERGECELLS[] = '';
2022-12-14 18:30:23 +03:00
$MERGECELLS[] = '<mergeCells count="' . count($this->sheets[$idx]['mergecells']) . '">';
foreach ($this->sheets[$idx]['mergecells'] as $m) {
$MERGECELLS[] = '<mergeCell ref="' . $m . '"/>';
2022-03-15 18:47:33 +03:00
}
$MERGECELLS[] = '</mergeCells>';
}
2022-02-05 15:32:10 +03:00
$HYPERLINKS = [];
2022-12-14 18:30:23 +03:00
if (count($this->sheets[$idx]['hyperlinks'])) {
2022-02-05 15:32:10 +03:00
$HYPERLINKS[] = '<hyperlinks>';
2022-12-14 18:30:23 +03:00
foreach ($this->sheets[$idx]['hyperlinks'] as $h) {
$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'] : '')) . '" />';
2022-02-05 15:32:10 +03:00
}
$HYPERLINKS[] = '</hyperlinks>';
}
2022-08-12 15:57:41 +03:00
2022-02-05 15:32:10 +03:00
//restore locale
setlocale(LC_NUMERIC, $_loc);
2022-12-14 18:30:23 +03:00
return str_replace(['{REF}', '{COLS}', '{ROWS}', '{AUTOFILTER}', '{MERGECELLS}', '{HYPERLINKS}'],
[$REF,
2022-08-12 15:57:41 +03:00
implode("\r\n", $COLS),
2022-12-14 18:30:23 +03:00
implode("\r\n", $ROWS),
2022-08-12 15:57:41 +03:00
$AUTOFILTER,
implode("\r\n", $MERGECELLS),
implode("\r\n", $HYPERLINKS)
],
2022-12-14 18:30:23 +03:00
$template);
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
public function num2name($num)
{
2022-02-05 15:32:10 +03:00
$numeric = ($num - 1) % 26;
2022-12-14 18:30:23 +03:00
$letter = chr(65 + $numeric);
$num2 = (int)(($num - 1) / 26);
if ($num2 > 0) {
return $this->num2name($num2) . $letter;
2020-07-29 18:50:38 +03:00
}
2022-02-05 15:32:10 +03:00
return $letter;
}
2020-07-29 18:50:38 +03:00
2022-12-14 18:30:23 +03:00
public function date2excel($year, $month, $day, $hours = 0, $minutes = 0, $seconds = 0)
{
2022-02-05 15:32:10 +03:00
$excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
2022-12-14 18:30:23 +03:00
if ((int)$year === 0) {
2022-02-05 15:32:10 +03:00
return $excelTime;
}
// self::CALENDAR_WINDOWS_1900
$excel1900isLeapYear = True;
2022-12-14 18:30:23 +03:00
if (($year === 1900) && ($month <= 2)) {
$excel1900isLeapYear = False;
}
2022-02-05 15:32:10 +03:00
$myExcelBaseDate = 2415020;
// Julian base date Adjustment
if ($month > 2) {
$month -= 3;
} else {
$month += 9;
--$year;
}
2022-12-14 18:30:23 +03:00
$century = substr($year, 0, 2);
$decade = substr($year, 2, 2);
2022-02-05 15:32:10 +03:00
// 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;
2022-12-14 18:30:23 +03:00
return (float)$excelDate + $excelTime;
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
public function setDefaultFont($name)
{
2022-02-05 15:32:10 +03:00
$this->defaultFont = $name;
return $this;
}
2022-12-14 18:30:23 +03:00
public function setDefaultFontSize($size)
{
2022-02-05 15:32:10 +03:00
$this->defaultFontSize = $size;
return $this;
}
2022-08-12 15:57:41 +03:00
2022-12-14 18:30:23 +03:00
public function autoFilter($range)
{
2022-08-12 15:57:41 +03:00
$this->sheets[$this->curSheet]['autofilter'] = $range;
return $this;
2022-08-06 20:13:06 +03:00
}
2022-08-12 15:57:41 +03:00
2022-12-14 18:30:23 +03:00
public function mergeCells($range)
{
2022-03-15 18:47:33 +03:00
$this->sheets[$this->curSheet]['mergecells'][] = $range;
return $this;
}
2022-12-14 18:30:23 +03:00
public function setColWidth($col, $width)
{
2022-06-01 09:54:28 +03:00
$this->sheets[$this->curSheet]['colwidth'][$col] = $width;
return $this;
}
2022-12-14 18:30:23 +03:00
public function esc($str)
{
2022-02-05 15:32:10 +03:00
// XML UTF-8: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
// but we use fast version
2022-12-14 18:30:23 +03:00
return str_replace(['&', '<', '>', "\x00", "\x03", "\x0B"], ['&amp;', '&lt;', '&gt;', '', '', ''], $str);
2022-02-05 15:32:10 +03:00
}
2022-12-14 18:30:23 +03:00
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;
}
2022-04-22 09:43:26 +03:00
}