SimpleXLSXGen.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. <?php
  2. /**
  3. * Class SimpleXLSXGen
  4. * Export data to MS Excel. PHP XLSX generator
  5. * Author: sergey.shuchkin@gmail.com
  6. */
  7. class SimpleXLSXGen
  8. {
  9. public $curSheet;
  10. protected $defaultFont;
  11. protected $defaultFontSize;
  12. protected $sheets;
  13. protected $template;
  14. protected $F, $F_KEYS; // fonts
  15. protected $XF, $XF_KEYS; // cellXfs
  16. protected $SI, $SI_KEYS; // shared strings
  17. const N_NORMAL = 0; // General
  18. const N_INT = 1; // 0
  19. const N_DEC = 2; // 0.00
  20. const N_PERCENT_INT = 9; // 0%
  21. const N_PRECENT_DEC = 10; // 0.00%
  22. const N_DATE = 14; // mm-dd-yy
  23. const N_TIME = 20; // h:mm
  24. const N_DATETIME = 22; // m/d/yy h:mm
  25. const F_NORMAL = 0;
  26. const F_HYPERLINK = 1;
  27. const F_BOLD = 2;
  28. const F_ITALIC = 4;
  29. const F_UNDERLINE = 8;
  30. const F_STRIKE = 16;
  31. const A_DEFAULT = 0;
  32. const A_LEFT = 1;
  33. const A_RIGHT = 2;
  34. const A_CENTER = 3;
  35. public function __construct()
  36. {
  37. $this->curSheet = -1;
  38. $this->defaultFont = 'Calibri';
  39. $this->sheets = [['name' => 'Sheet1', 'rows' => [], 'hyperlinks' => []]];
  40. $this->SI = []; // sharedStrings index
  41. $this->SI_KEYS = []; // & keys
  42. $this->F = [self::F_NORMAL]; // fonts
  43. $this->F_KEYS = [0]; // & keys
  44. $this->XF = [[self::N_NORMAL, self::F_NORMAL, self::A_DEFAULT]]; // styles
  45. $this->XF_KEYS = ['N0F0A0' => 0]; // & keys
  46. $this->template = [
  47. '_rels/.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  48. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  49. <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
  50. <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
  51. <Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>
  52. </Relationships>',
  53. 'docProps/app.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  54. <Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">
  55. <TotalTime>0</TotalTime>
  56. <Application>' . __CLASS__ . '</Application></Properties>',
  57. 'docProps/core.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  58. <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">
  59. <dcterms:created xsi:type="dcterms:W3CDTF">{DATE}</dcterms:created>
  60. <dc:language>en-US</dc:language>
  61. <dcterms:modified xsi:type="dcterms:W3CDTF">{DATE}</dcterms:modified>
  62. <cp:revision>1</cp:revision>
  63. </cp:coreProperties>',
  64. 'xl/_rels/workbook.xml.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  65. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
  66. <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
  67. {SHEETS}',
  68. 'xl/worksheets/sheet1.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  69. <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"
  70. xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
  71. ><dimension ref="{REF}"/>{COLS}<sheetData>{ROWS}</sheetData>{HYPERLINKS}</worksheet>',
  72. 'xl/worksheets/_rels/sheet1.xml.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  73. <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{HYPERLINKS}</Relationships>',
  74. 'xl/sharedStrings.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  75. <sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="{CNT}" uniqueCount="{CNT}">{STRINGS}</sst>',
  76. 'xl/styles.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  77. <styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
  78. {FONTS}
  79. <fills count="1"><fill><patternFill patternType="none"/></fill></fills>
  80. <borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders>
  81. <cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" /></cellStyleXfs>
  82. {XF}
  83. <cellStyles count="1">
  84. <cellStyle name="Normal" xfId="0" builtinId="0"/>
  85. </cellStyles>
  86. </styleSheet>',
  87. 'xl/workbook.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  88. <workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
  89. <fileVersion appName="' . __CLASS__ . '"/><sheets>
  90. {SHEETS}
  91. </sheets></workbook>',
  92. '[Content_Types].xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  93. <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
  94. <Override PartName="/rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
  95. <Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>
  96. <Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>
  97. <Override PartName="/xl/_rels/workbook.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
  98. <Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>
  99. <Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
  100. <Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>
  101. {TYPES}
  102. </Types>',
  103. ];
  104. // <col min="1" max="1" width="22.1796875" bestFit="1" customWidth="1"/>
  105. // <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>
  106. // <si><t>Простой шаблон</t></si><si><t>Будем делать генератор</t></si>
  107. }
  108. public static function fromArray(array $rows, $sheetName = null)
  109. {
  110. $xlsx = new static();
  111. return $xlsx->addSheet($rows, $sheetName);
  112. }
  113. public function addSheet(array $rows, $name = null)
  114. {
  115. $this->curSheet++;
  116. if ($name === null) { // autogenerated sheet names
  117. $name = 'Sheet' . ($this->curSheet + 1);
  118. } else {
  119. $names = [];
  120. foreach ($this->sheets as $sh) {
  121. $names[mb_strtoupper($sh['name'])] = 1;
  122. }
  123. for ($i = 0; $i < 100; $i++) {
  124. $new_name = ($i === 0) ? $name : $name . ' (' . $i . ')';
  125. $NEW_NAME = mb_strtoupper($new_name);
  126. if (!isset($names[$NEW_NAME])) {
  127. $name = $new_name;
  128. break;
  129. }
  130. }
  131. }
  132. $this->sheets[$this->curSheet] = ['name' => $name, 'hyperlinks' => []];
  133. if (is_array($rows) && isset($rows[0]) && is_array($rows[0])) {
  134. $this->sheets[$this->curSheet]['rows'] = $rows;
  135. } else {
  136. $this->sheets[$this->curSheet]['rows'] = [];
  137. }
  138. return $this;
  139. }
  140. public function __toString()
  141. {
  142. $fh = fopen('php://memory', 'wb');
  143. if (!$fh) {
  144. return '';
  145. }
  146. if (!$this->_write($fh)) {
  147. fclose($fh);
  148. return '';
  149. }
  150. $size = ftell($fh);
  151. fseek($fh, 0);
  152. return (string) fread($fh, $size);
  153. }
  154. public function saveAs($filename)
  155. {
  156. $fh = fopen($filename, 'wb');
  157. if (!$fh) {
  158. return false;
  159. }
  160. if (!$this->_write($fh)) {
  161. fclose($fh);
  162. return false;
  163. }
  164. fclose($fh);
  165. return true;
  166. }
  167. public function download()
  168. {
  169. return $this->downloadAs(gmdate('YmdHi') . '.xlsx');
  170. }
  171. public function downloadAs($filename)
  172. {
  173. $fh = fopen('php://memory', 'wb');
  174. if (!$fh) {
  175. return false;
  176. }
  177. if (!$this->_write($fh)) {
  178. fclose($fh);
  179. return false;
  180. }
  181. $size = ftell($fh);
  182. header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  183. header('Content-Disposition: attachment; filename="' . $filename . '"');
  184. header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T', time()));
  185. header('Content-Length: ' . $size);
  186. while (ob_get_level()) {
  187. ob_end_clean();
  188. }
  189. fseek($fh, 0);
  190. fpassthru($fh);
  191. fclose($fh);
  192. return true;
  193. }
  194. protected function _write($fh)
  195. {
  196. $dirSignatureE = "\x50\x4b\x05\x06"; // end of central dir signature
  197. $zipComments = 'Generated by ' . __CLASS__ . ' PHP class, thanks sergey.shuchkin@gmail.com';
  198. if (!$fh) {
  199. return false;
  200. }
  201. $cdrec = ''; // central directory content
  202. $entries = 0; // number of zipped files
  203. $cnt_sheets = count($this->sheets);
  204. foreach ($this->template as $cfilename => $template) {
  205. if ($cfilename === 'xl/_rels/workbook.xml.rels') {
  206. $s = '';
  207. for ($i = 0; $i < $cnt_sheets; $i++) {
  208. $s .= '<Relationship Id="rId' . ($i + 2) . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"' .
  209. ' Target="worksheets/sheet' . ($i + 1) . ".xml\"/>\n";
  210. }
  211. $s .= '<Relationship Id="rId' . ($i + 2) . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/></Relationships>';
  212. $template = str_replace('{SHEETS}', $s, $template);
  213. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  214. $entries++;
  215. } elseif ($cfilename === 'xl/workbook.xml') {
  216. $s = '';
  217. foreach ($this->sheets as $k => $v) {
  218. $s .= '<sheet name="' . $this->esc($v['name']) . '" sheetId="' . ($k + 1) . '" state="visible" r:id="rId' . ($k + 2) . '"/>';
  219. }
  220. $template = str_replace('{SHEETS}', $s, $template);
  221. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  222. $entries++;
  223. } elseif ($cfilename === 'docProps/core.xml') {
  224. $template = str_replace('{DATE}', gmdate('Y-m-d\TH:i:s\Z'), $template);
  225. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  226. $entries++;
  227. } elseif ($cfilename === 'xl/sharedStrings.xml') {
  228. if (!count($this->SI)) {
  229. $this->SI[] = 'No Data';
  230. }
  231. $si_cnt = count($this->SI);
  232. $si = '<si><t>' . implode("</t></si>\r\n<si><t>", $this->SI) . '</t></si>';
  233. $template = str_replace(['{CNT}', '{STRINGS}'], [$si_cnt, $si], $template);
  234. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  235. $entries++;
  236. } elseif ($cfilename === 'xl/worksheets/sheet1.xml') {
  237. foreach ($this->sheets as $k => $v) {
  238. $filename = 'xl/worksheets/sheet' . ($k + 1) . '.xml';
  239. $xml = $this->_sheetToXML($k, $template);
  240. $this->_writeEntry($fh, $cdrec, $filename, $xml);
  241. $entries++;
  242. }
  243. $xml = null;
  244. } elseif ($cfilename === 'xl/worksheets/_rels/sheet1.xml.rels') {
  245. foreach ($this->sheets as $k => $v) {
  246. if (count($v['hyperlinks'])) {
  247. $RH = [];
  248. $filename = 'xl/worksheets/_rels/sheet' . ($k + 1) . '.xml.rels';
  249. foreach ($v['hyperlinks'] as $h) {
  250. $RH[] = '<Relationship Id="' . $h['ID'] . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="' . $this->esc($h['H']) . '" TargetMode="External"/>';
  251. }
  252. $xml = str_replace('{HYPERLINKS}', implode("\r\n", $RH), $template);
  253. $this->_writeEntry($fh, $cdrec, $filename, $xml);
  254. $entries++;
  255. }
  256. }
  257. $xml = null;
  258. } elseif ($cfilename === '[Content_Types].xml') {
  259. $TYPES = ['<Override PartName="/_rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'];
  260. foreach ($this->sheets as $k => $v) {
  261. $TYPES[] = '<Override PartName="/xl/worksheets/sheet' . ($k + 1) .
  262. '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
  263. if (count($v['hyperlinks'])) {
  264. $TYPES[] = '<Override PartName="/xl/worksheets/_rels/sheet' . ($k + 1) . '.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
  265. }
  266. }
  267. $template = str_replace('{TYPES}', implode("\r\n", $TYPES), $template);
  268. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  269. $entries++;
  270. } elseif ($cfilename === 'xl/styles.xml') {
  271. $FONTS = ['<fonts count="' . count($this->F) . '">'];
  272. foreach ($this->F as $f) {
  273. $FONTS[] = '<font><name val="' . $this->defaultFont . '"/><family val="2"/>'
  274. . ($this->defaultFontSize ? '<sz val="' . $this->defaultFontSize . '"/>' : '')
  275. . ($f & self::F_BOLD ? '<b/>' : '')
  276. . ($f & self::F_ITALIC ? '<i/>' : '')
  277. . ($f & self::F_UNDERLINE ? '<u/>' : '')
  278. . ($f & self::F_STRIKE ? '<strike/>' : '')
  279. . ($f & self::F_HYPERLINK ? '<color rgb="FF0563C1"/><u/>' : '')
  280. . '</font>';
  281. }
  282. $FONTS[] = '</fonts>';
  283. $XF = ['<cellXfs count="' . count($this->XF) . '">'];
  284. foreach ($this->XF as $xf) {
  285. $align = ($xf[2] === self::A_LEFT ? ' applyAlignment="1"><alignment horizontal="left"/>' : '')
  286. . ($xf[2] === self::A_RIGHT ? ' applyAlignment="1"><alignment horizontal="right"/>' : '')
  287. . ($xf[2] === self::A_CENTER ? ' applyAlignment="1"><alignment horizontal="center"/>' : '');
  288. $XF[] = '<xf numFmtId="' . $xf[0] . '" fontId="' . $xf[1] . '" fillId="0" borderId="0" xfId="0"'
  289. . ($xf[0] > 0 ? ' applyNumberFormat="1"' : '')
  290. . ($align ? $align . '</xf>' : '/>');
  291. }
  292. $XF[] = '</cellXfs>';
  293. $template = str_replace(['{FONTS}', '{XF}'], [implode("\r\n", $FONTS), implode("\r\n", $XF)], $template);
  294. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  295. $entries++;
  296. } else {
  297. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  298. $entries++;
  299. }
  300. }
  301. $before_cd = ftell($fh);
  302. fwrite($fh, $cdrec);
  303. // end of central dir
  304. fwrite($fh, $dirSignatureE);
  305. fwrite($fh, pack('v', 0)); // number of this disk
  306. fwrite($fh, pack('v', 0)); // number of the disk with the start of the central directory
  307. fwrite($fh, pack('v', $entries)); // total # of entries "on this disk"
  308. fwrite($fh, pack('v', $entries)); // total # of entries overall
  309. fwrite($fh, pack('V', mb_strlen($cdrec, '8bit'))); // size of central dir
  310. fwrite($fh, pack('V', $before_cd)); // offset to start of central dir
  311. fwrite($fh, pack('v', mb_strlen($zipComments, '8bit'))); // .zip file comment length
  312. fwrite($fh, $zipComments);
  313. return true;
  314. }
  315. protected function _writeEntry($fh, &$cdrec, $cfilename, $data)
  316. {
  317. $zipSignature = "\x50\x4b\x03\x04"; // local file header signature
  318. $dirSignature = "\x50\x4b\x01\x02"; // central dir header signature
  319. $e = [];
  320. $e['uncsize'] = mb_strlen($data, '8bit');
  321. // if data to compress is too small, just store it
  322. if ($e['uncsize'] < 256) {
  323. $e['comsize'] = $e['uncsize'];
  324. $e['vneeded'] = 10;
  325. $e['cmethod'] = 0;
  326. $zdata = $data;
  327. } else { // otherwise, compress it
  328. $zdata = gzcompress($data);
  329. $zdata = substr(substr($zdata, 0, -4), 2); // fix crc bug (thanks to Eric Mueller)
  330. $e['comsize'] = mb_strlen($zdata, '8bit');
  331. $e['vneeded'] = 10;
  332. $e['cmethod'] = 8;
  333. }
  334. $e['bitflag'] = 0;
  335. $e['crc_32'] = crc32($data);
  336. // Convert date and time to DOS Format, and set then
  337. $lastmod_timeS = str_pad(decbin(date('s') >= 32 ? date('s') - 32 : date('s')), 5, '0', STR_PAD_LEFT);
  338. $lastmod_timeM = str_pad(decbin(date('i')), 6, '0', STR_PAD_LEFT);
  339. $lastmod_timeH = str_pad(decbin(date('H')), 5, '0', STR_PAD_LEFT);
  340. $lastmod_dateD = str_pad(decbin(date('d')), 5, '0', STR_PAD_LEFT);
  341. $lastmod_dateM = str_pad(decbin(date('m')), 4, '0', STR_PAD_LEFT);
  342. $lastmod_dateY = str_pad(decbin(date('Y') - 1980), 7, '0', STR_PAD_LEFT);
  343. # echo "ModTime: $lastmod_timeS-$lastmod_timeM-$lastmod_timeH (".date("s H H").")\n";
  344. # echo "ModDate: $lastmod_dateD-$lastmod_dateM-$lastmod_dateY (".date("d m Y").")\n";
  345. $e['modtime'] = bindec("$lastmod_timeH$lastmod_timeM$lastmod_timeS");
  346. $e['moddate'] = bindec("$lastmod_dateY$lastmod_dateM$lastmod_dateD");
  347. $e['offset'] = ftell($fh);
  348. fwrite($fh, $zipSignature);
  349. fwrite($fh, pack('s', $e['vneeded'])); // version_needed
  350. fwrite($fh, pack('s', $e['bitflag'])); // general_bit_flag
  351. fwrite($fh, pack('s', $e['cmethod'])); // compression_method
  352. fwrite($fh, pack('s', $e['modtime'])); // lastmod_time
  353. fwrite($fh, pack('s', $e['moddate'])); // lastmod_date
  354. fwrite($fh, pack('V', $e['crc_32'])); // crc-32
  355. fwrite($fh, pack('I', $e['comsize'])); // compressed_size
  356. fwrite($fh, pack('I', $e['uncsize'])); // uncompressed_size
  357. fwrite($fh, pack('s', mb_strlen($cfilename, '8bit'))); // file_name_length
  358. fwrite($fh, pack('s', 0)); // extra_field_length
  359. fwrite($fh, $cfilename); // file_name
  360. // ignoring extra_field
  361. fwrite($fh, $zdata);
  362. // Append it to central dir
  363. $e['external_attributes'] = (substr($cfilename, -1) === '/' && !$zdata) ? 16 : 32; // Directory or file name
  364. $e['comments'] = '';
  365. $cdrec .= $dirSignature;
  366. $cdrec .= "\x0\x0"; // version made by
  367. $cdrec .= pack('v', $e['vneeded']); // version needed to extract
  368. $cdrec .= "\x0\x0"; // general bit flag
  369. $cdrec .= pack('v', $e['cmethod']); // compression method
  370. $cdrec .= pack('v', $e['modtime']); // lastmod time
  371. $cdrec .= pack('v', $e['moddate']); // lastmod date
  372. $cdrec .= pack('V', $e['crc_32']); // crc32
  373. $cdrec .= pack('V', $e['comsize']); // compressed filesize
  374. $cdrec .= pack('V', $e['uncsize']); // uncompressed filesize
  375. $cdrec .= pack('v', mb_strlen($cfilename, '8bit')); // file name length
  376. $cdrec .= pack('v', 0); // extra field length
  377. $cdrec .= pack('v', mb_strlen($e['comments'], '8bit')); // file comment length
  378. $cdrec .= pack('v', 0); // disk number start
  379. $cdrec .= pack('v', 0); // internal file attributes
  380. $cdrec .= pack('V', $e['external_attributes']); // internal file attributes
  381. $cdrec .= pack('V', $e['offset']); // relative offset of local header
  382. $cdrec .= $cfilename;
  383. $cdrec .= $e['comments'];
  384. }
  385. protected function _sheetToXML($idx, $template)
  386. {
  387. // locale floats fr_FR 1.234,56 -> 1234.56
  388. $_loc = setlocale(LC_NUMERIC, 0);
  389. setlocale(LC_NUMERIC, 'C');
  390. $COLS = [];
  391. $ROWS = [];
  392. if (count($this->sheets[$idx]['rows'])) {
  393. $COLS[] = '<cols>';
  394. $CUR_ROW = 0;
  395. $COL = [];
  396. foreach ($this->sheets[$idx]['rows'] as $r) {
  397. $CUR_ROW++;
  398. $row = '<row r="' . $CUR_ROW . '">';
  399. $CUR_COL = 0;
  400. foreach ($r as $v) {
  401. $CUR_COL++;
  402. if (!isset($COL[$CUR_COL])) {
  403. $COL[$CUR_COL] = 0;
  404. }
  405. if ($v === null || $v === '') {
  406. continue;
  407. }
  408. $cname = $this->num2name($CUR_COL) . $CUR_ROW;
  409. $ct = $cv = null;
  410. $N = $F = $A = 0;
  411. if (is_string($v)) {
  412. if ($v[0] === "\0") { // RAW value as string
  413. $v = substr($v, 1);
  414. $vl = mb_strlen($v);
  415. } else {
  416. if (strpos($v, '<') !== false) { // tags?
  417. if (strpos($v, '<b>') !== false) {
  418. $F += self::F_BOLD;
  419. }
  420. if (strpos($v, '<i>') !== false) {
  421. $F += self::F_ITALIC;
  422. }
  423. if (strpos($v, '<u>') !== false) {
  424. $F += self::F_UNDERLINE;
  425. }
  426. if (strpos($v, '<s>') !== false) {
  427. $F += self::F_STRIKE;
  428. }
  429. if (strpos($v, '<left>') !== false) {
  430. $A += self::A_LEFT;
  431. }
  432. if (strpos($v, '<center>') !== false) {
  433. $A += self::A_CENTER;
  434. }
  435. if (strpos($v, '<right>') !== false) {
  436. $A += self::A_RIGHT;
  437. }
  438. if (preg_match('/<a href="(https?:\/\/[^"]+)">(.*?)<\/a>/i', $v, $m)) {
  439. $h = explode('#', $m[1]);
  440. $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . (count($this->sheets[$idx]['hyperlinks']) + 1), 'R' => $cname, 'H' => $h[0], 'L' => isset($h[1]) ? $h[1] : ''];
  441. $F = self::F_HYPERLINK; // Hyperlink
  442. }
  443. if (preg_match('/<a href="(mailto?:[^"]+)">(.*?)<\/a>/i', $v, $m)) {
  444. $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . (count($this->sheets[$idx]['hyperlinks']) + 1), 'R' => $cname, 'H' => $m[1], 'L' => ''];
  445. $F = self::F_HYPERLINK; // mailto hyperlink
  446. }
  447. $v = strip_tags($v);
  448. } // tags
  449. $vl = mb_strlen($v);
  450. if ($v === '0' || preg_match('/^[-+]?[1-9]\d{0,14}$/', $v)) { // Integer as General
  451. $cv = ltrim($v, '+');
  452. if ($vl > 10) {
  453. $N = self::N_INT; // [1] 0
  454. }
  455. } elseif (preg_match('/^[-+]?(0|[1-9]\d*)\.(\d+)$/', $v, $m)) {
  456. $cv = ltrim($v, '+');
  457. if (strlen($m[2]) < 3) {
  458. $N = self::N_DEC;
  459. }
  460. } elseif (preg_match('/^([-+]?\d+)%$/', $v, $m)) {
  461. $cv = round($m[1] / 100, 2);
  462. $N = self::N_PERCENT_INT; // [9] 0%
  463. } elseif (preg_match('/^([-+]?\d+\.\d+)%$/', $v, $m)) {
  464. $cv = round($m[1] / 100, 4);
  465. $N = self::N_PRECENT_DEC; // [10] 0.00%
  466. } elseif (preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d)$/', $v, $m)) {
  467. $cv = $this->date2excel($m[1], $m[2], $m[3]);
  468. $N = self::N_DATE; // [14] mm-dd-yy
  469. } elseif (preg_match('/^(\d\d)\/(\d\d)\/(\d\d\d\d)$/', $v, $m)) {
  470. $cv = $this->date2excel($m[3], $m[2], $m[1]);
  471. $N = self::N_DATE; // [14] mm-dd-yy
  472. } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $v, $m)) {
  473. $cv = $this->date2excel(0, 0, 0, $m[1], $m[2], $m[3]);
  474. $N = self::N_TIME; // time
  475. } elseif (preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$/', $v, $m)) {
  476. $cv = $this->date2excel($m[1], $m[2], $m[3], $m[4], $m[5], $m[6]);
  477. $N = self::N_DATETIME; // [22] m/d/yy h:mm
  478. } elseif (preg_match('/^(\d\d)\/(\d\d)\/(\d\d\d\d) (\d\d):(\d\d):(\d\d)$/', $v, $m)) {
  479. $cv = $this->date2excel($m[3], $m[2], $m[1], $m[4], $m[5], $m[6]);
  480. $N = self::N_DATETIME; // [22] m/d/yy h:mm
  481. } elseif (preg_match('/^[0-9+-.]+$/', $v)) { // Long ?
  482. $A = self::A_RIGHT;
  483. } elseif (preg_match('/^https?:\/\/\S+$/i', $v)) {
  484. $h = explode('#', $v);
  485. $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . (count($this->sheets[$idx]['hyperlinks']) + 1), 'R' => $cname, 'H' => $h[0], 'L' => isset($h[1]) ? $h[1] : ''];
  486. $F = self::F_HYPERLINK; // Hyperlink
  487. } elseif (preg_match("/^[a-zA-Z0-9_\.\-]+@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/", $v)) {
  488. $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . (count($this->sheets[$idx]['hyperlinks']) + 1), 'R' => $cname, 'H' => 'mailto:' . $v, 'L' => ''];
  489. $F = self::F_HYPERLINK; // Hyperlink
  490. }
  491. }
  492. if (!$cv) {
  493. $v = $this->esc($v);
  494. if (mb_strlen($v) > 160) {
  495. $ct = 'inlineStr';
  496. $cv = $v;
  497. } else {
  498. $ct = 's'; // shared string
  499. $cv = false;
  500. $skey = '~' . $v;
  501. if (isset($this->SI_KEYS[$skey])) {
  502. $cv = $this->SI_KEYS[$skey];
  503. }
  504. if ($cv === false) {
  505. $this->SI[] = $v;
  506. $cv = count($this->SI) - 1;
  507. $this->SI_KEYS[$skey] = $cv;
  508. }
  509. }
  510. }
  511. } elseif (is_int($v)) {
  512. $vl = mb_strlen((string) $v);
  513. $cv = $v;
  514. } elseif (is_float($v)) {
  515. $vl = mb_strlen((string) $v);
  516. $cv = $v;
  517. } elseif ($v instanceof DateTime) {
  518. $vl = 16;
  519. $cv = $this->date2excel($v->format('Y'), $v->format('m'), $v->format('d'), $v->format('H'), $v->format('i'), $v->format('s'));
  520. $N = self::N_DATETIME; // [22] m/d/yy h:mm
  521. } else {
  522. continue;
  523. }
  524. $COL[$CUR_COL] = max($vl, $COL[$CUR_COL]);
  525. $cs = 0;
  526. if ($N + $F + $A > 0) {
  527. if (isset($this->F_KEYS[$F])) {
  528. $cf = $this->F_KEYS[$F];
  529. } else {
  530. $cf = count($this->F);
  531. $this->F_KEYS[$F] = $cf;
  532. $this->F[] = $F;
  533. }
  534. $NFA = 'N' . $N . 'F' . $cf . 'A' . $A;
  535. if (isset($this->XF_KEYS[$NFA])) {
  536. $cs = $this->XF_KEYS[$NFA];
  537. }
  538. if ($cs === 0) {
  539. $cs = count($this->XF);
  540. $this->XF_KEYS[$NFA] = $cs;
  541. $this->XF[] = [$N, $cf, $A];
  542. }
  543. }
  544. $row .= '<c r="' . $cname . '"' . ($ct ? ' t="' . $ct . '"' : '') . ($cs ? ' s="' . $cs . '"' : '') . '>'
  545. . ($ct === 'inlineStr' ? '<is><t>' . $cv . '</t></is>' : '<v>' . $cv . '</v>') . "</c>\r\n";
  546. }
  547. $ROWS[] = $row . "</row>\r\n";
  548. }
  549. foreach ($COL as $k => $max) {
  550. $COLS[] = '<col min="' . $k . '" max="' . $k . '" width="' . min($max + 1, 60) . '" />';
  551. }
  552. $COLS[] = '</cols>';
  553. $REF = 'A1:' . $this->num2name(count($COLS)) . $CUR_ROW;
  554. } else {
  555. $ROWS[] = '<row r="1"><c r="A1" t="s"><v>0</v></c></row>';
  556. $REF = 'A1:A1';
  557. }
  558. $HYPERLINKS = [];
  559. if (count($this->sheets[$idx]['hyperlinks'])) {
  560. $HYPERLINKS[] = '<hyperlinks>';
  561. foreach ($this->sheets[$idx]['hyperlinks'] as $h) {
  562. $HYPERLINKS[] = '<hyperlink ref="' . $h['R'] . '" r:id="' . $h['ID'] . '" location="' . $this->esc($h['L']) . '" display="' . $this->esc($h['H'] . ($h['L'] ? ' - ' . $h['L'] : '')) . '" />';
  563. }
  564. $HYPERLINKS[] = '</hyperlinks>';
  565. }
  566. //restore locale
  567. setlocale(LC_NUMERIC, $_loc);
  568. return str_replace(
  569. ['{REF}', '{COLS}', '{ROWS}', '{HYPERLINKS}'],
  570. [$REF, implode("\r\n", $COLS), implode("\r\n", $ROWS), implode("\r\n", $HYPERLINKS)],
  571. $template
  572. );
  573. }
  574. public function num2name($num)
  575. {
  576. $numeric = ($num - 1) % 26;
  577. $letter = chr(65 + $numeric);
  578. $num2 = (int) (($num - 1) / 26);
  579. if ($num2 > 0) {
  580. return $this->num2name($num2) . $letter;
  581. }
  582. return $letter;
  583. }
  584. public function date2excel($year, $month, $day, $hours = 0, $minutes = 0, $seconds = 0)
  585. {
  586. $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
  587. if ($year === 0) {
  588. return $excelTime;
  589. }
  590. // self::CALENDAR_WINDOWS_1900
  591. $excel1900isLeapYear = True;
  592. if (((int)$year === 1900) && ($month <= 2)) {
  593. $excel1900isLeapYear = False;
  594. }
  595. $myExcelBaseDate = 2415020;
  596. // Julian base date Adjustment
  597. if ($month > 2) {
  598. $month -= 3;
  599. } else {
  600. $month += 9;
  601. --$year;
  602. }
  603. // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
  604. $century = substr($year, 0, 2);
  605. $decade = substr($year, 2, 2);
  606. $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myExcelBaseDate + $excel1900isLeapYear;
  607. return (float) $excelDate + $excelTime;
  608. }
  609. public function setDefaultFont($name)
  610. {
  611. $this->defaultFont = $name;
  612. return $this;
  613. }
  614. public function setDefaultFontSize($size)
  615. {
  616. $this->defaultFontSize = $size;
  617. return $this;
  618. }
  619. public function esc($str)
  620. {
  621. // XML UTF-8: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
  622. // but we use fast version
  623. return str_replace(['&', '<', '>', "\x00", "\x03", "\x0B"], ['&amp;', '&lt;', '&gt;', '', '', ''], $str);
  624. }
  625. }