You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1333 lines
64 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. <?php
  2. /** @noinspection UnknownInspectionInspection */
  3. /* PHP5.6 */
  4. /** @noinspection PowerOperatorCanBeUsedInspection */
  5. /* PHP7 */
  6. /** @noinspection NullCoalescingOperatorCanBeUsedInspection */
  7. /** @noinspection PhpIssetCanBeReplacedWithCoalesceInspection */
  8. /* PHP8 */
  9. /** @noinspection ReturnTypeCanBeDeclaredInspection */
  10. /** @noinspection PhpMissingClassConstantTypeInspection */
  11. /** @noinspection PhpMissingFieldTypeInspection */
  12. /** @noinspection PhpMissingParamTypeInspection */
  13. /** @noinspection PhpMissingReturnTypeInspection */
  14. /** @noinspection PhpStrFunctionsInspection */
  15. /** @noinspection AccessModifierPresentedInspection */
  16. namespace Shuchkin;
  17. /**
  18. * Class SimpleXLSXGen
  19. * Export data to MS Excel. PHP XLSX generator
  20. * Author: sergey.shuchkin@gmail.com
  21. */
  22. class SimpleXLSXGen
  23. {
  24. public $curSheet;
  25. protected $defaultFont;
  26. protected $defaultFontSize;
  27. protected $rtl;
  28. protected $sheets;
  29. protected $template;
  30. protected $NF; // numFmts
  31. protected $NF_KEYS;
  32. protected $XF; // cellXfs
  33. protected $XF_KEYS;
  34. protected $BR_STYLE;
  35. protected $SI; // shared strings
  36. protected $SI_KEYS;
  37. protected $rIndex;
  38. protected $title;
  39. protected $subject;
  40. protected $author;
  41. protected $company;
  42. protected $manager;
  43. protected $description;
  44. protected $application;
  45. protected $keywords;
  46. protected $category;
  47. protected $language;
  48. protected $lastModifiedBy;
  49. const N_NORMAL = 0; // General
  50. const N_INT = 1; // 0
  51. const N_DEC = 2; // 0.00
  52. const N_PERCENT_INT = 9; // 0%
  53. const N_PRECENT_DEC = 10; // 0.00%
  54. const N_DATE = 14; // mm-dd-yy
  55. const N_TIME = 20; // h:mm
  56. const N_RUB = 164;
  57. const N_DOLLAR = 165;
  58. const N_EURO = 166;
  59. const N_DATETIME = 22; // m/d/yy h:mm
  60. const N_CUSTOM = 197;
  61. const F_NORMAL = 0;
  62. const F_HYPERLINK = 1;
  63. const F_BOLD = 2;
  64. const F_ITALIC = 4;
  65. const F_UNDERLINE = 8;
  66. const F_STRIKE = 16;
  67. const F_COLOR = 32;
  68. const FL_NONE = 0; // none
  69. const FL_SOLID = 1; // solid
  70. const FL_MEDIUM_GRAY = 2; // mediumGray
  71. const FL_DARK_GRAY = 4; // darkGray
  72. const FL_LIGHT_GRAY = 8; // lightGray
  73. const FL_GRAY_125 = 16; // gray125
  74. const FL_COLOR = 32;
  75. const A_DEFAULT = 0;
  76. const A_LEFT = 1;
  77. const A_RIGHT = 2;
  78. const A_CENTER = 4;
  79. const A_TOP = 8;
  80. const A_MIDDLE = 16;
  81. const A_BOTTOM = 32;
  82. const A_WRAPTEXT = 64;
  83. const B_NONE = 0;
  84. const B_THIN = 1;
  85. const B_MEDIUM = 2;
  86. //const
  87. const B_DASHED = 3;
  88. const B_DOTTED = 4;
  89. const B_THICK = 5;
  90. const B_DOUBLE = 6;
  91. const B_HAIR = 7;
  92. const B_MEDIUM_DASHED = 8;
  93. const B_DASH_DOT = 9;
  94. const B_MEDIUM_DASH_DOT = 10;
  95. const B_DASH_DOT_DOT = 11;
  96. const B_MEDIUM_DASH_DOT_DOT = 12;
  97. const B_SLANT_DASH_DOT = 13;
  98. public function __construct()
  99. {
  100. $this->subject = '';
  101. $this->title = '';
  102. $this->author = '';
  103. $this->company = '';
  104. $this->manager = '';
  105. $this->description = '';
  106. $this->keywords = '';
  107. $this->category = '';
  108. $this->language = 'en-US';
  109. $this->lastModifiedBy = '';
  110. $this->application = __CLASS__;
  111. $this->curSheet = -1;
  112. $this->defaultFont = 'Calibri';
  113. $this->defaultFontSize = 10;
  114. $this->rtl = false;
  115. $this->sheets = [];
  116. $this->SI = []; // sharedStrings index
  117. $this->SI_KEYS = []; // & keys
  118. // https://c-rex.net/projects/samples/ooxml/e1/Part4/OOXML_P4_DOCX_numFmts_topic_ID0E6KK6.html
  119. $this->NF = [
  120. self::N_RUB => '#,##0.00\ "₽"',
  121. self::N_DOLLAR => '[$$-1]#,##0.00',
  122. self::N_EURO => '#,##0.00\ [$€-1]'
  123. ];
  124. $this->NF_KEYS = array_flip($this->NF);
  125. $this->BR_STYLE = [
  126. self::B_NONE => 'none',
  127. self::B_THIN => 'thin',
  128. self::B_MEDIUM => 'medium',
  129. self::B_DASHED => 'dashed',
  130. self::B_DOTTED => 'dotted',
  131. self::B_THICK => 'thick',
  132. self::B_DOUBLE => 'double',
  133. self::B_HAIR => 'hair',
  134. self::B_MEDIUM_DASHED => 'mediumDashed',
  135. self::B_DASH_DOT => 'dashDot',
  136. self::B_MEDIUM_DASH_DOT => 'mediumDashDot',
  137. self::B_DASH_DOT_DOT => 'dashDotDot',
  138. self::B_MEDIUM_DASH_DOT_DOT => 'mediumDashDotDot',
  139. self::B_SLANT_DASH_DOT => 'slantDashDot'
  140. ];
  141. $this->XF = [ // styles 0 - num fmt, 1 - align, 2 - font, 3 - fill, 4 - font color, 5 - bgcolor, 6 - border, 7 - font size
  142. [self::N_NORMAL, self::A_DEFAULT, self::F_NORMAL, self::FL_NONE, 0, 0, '', 0],
  143. [self::N_NORMAL, self::A_DEFAULT, self::F_NORMAL, self::FL_GRAY_125, 0, 0, '', 0], // hack
  144. ];
  145. $this->XF_KEYS[implode('-', $this->XF[0])] = 0; // & keys
  146. $this->XF_KEYS[implode('-', $this->XF[1])] = 1;
  147. $this->template = [
  148. '_rels/.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\r\n"
  149. .'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'."\r\n"
  150. .'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>'."\r\n"
  151. .'<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>'."\r\n"
  152. .'<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>'."\r\n"
  153. .'</Relationships>',
  154. 'docProps/app.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\r\n"
  155. .'<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties">'."\r\n"
  156. .'<TotalTime>0</TotalTime>'."\r\n"
  157. .'<Application>{APP}</Application>'."\r\n"
  158. .'<Company>{COMPANY}</Company>'."\r\n"
  159. .'<Manager>{MANAGER}</Manager>'."\r\n"
  160. .'</Properties>',
  161. 'docProps/core.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\r\n"
  162. .'<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">'."\r\n"
  163. .'<dcterms:created xsi:type="dcterms:W3CDTF">{DATE}</dcterms:created>'."\r\n"
  164. .'<dc:title>{TITLE}</dc:title>'."\r\n"
  165. .'<dc:subject>{SUBJECT}</dc:subject>'."\r\n"
  166. .'<dc:creator>{AUTHOR}</dc:creator>'."\r\n"
  167. .'<cp:lastModifiedBy>{LAST_MODIFY_BY}</cp:lastModifiedBy>'."\r\n"
  168. .'<cp:keywords>{KEYWORD}</cp:keywords>'."\r\n"
  169. .'<dc:description>{DESCRIPTION}</dc:description>'."\r\n"
  170. .'<cp:category>{CATEGORY}</cp:category>'."\r\n"
  171. .'<dc:language>{LANGUAGE}</dc:language>'."\r\n"
  172. .'<dcterms:modified xsi:type="dcterms:W3CDTF">{DATE}</dcterms:modified>'."\r\n"
  173. .'<cp:revision>1</cp:revision>'."\r\n"
  174. .'</cp:coreProperties>',
  175. 'xl/_rels/workbook.xml.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\r\n"
  176. .'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
  177. ."\r\n{RELS}\r\n</Relationships>",
  178. 'xl/worksheets/sheet1.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\r\n"
  179. . '<worksheet' . "\r\n"
  180. . ' xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"' . "\r\n"
  181. . ' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"'."\r\n"
  182. . ' xmlns:mx="http://schemas.microsoft.com/office/mac/excel/2008/main"' . "\r\n"
  183. . ' xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"' . "\r\n"
  184. . ' xmlns:mv="urn:schemas-microsoft-com:mac:vml"' . "\r\n"
  185. . ' xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main"' . "\r\n"
  186. . ' xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main"' . "\r\n"
  187. . ' xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"' . "\r\n"
  188. . ' xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main">' . "\r\n"
  189. .'<dimension ref="{REF}"/>'."\r\n"
  190. ."{SHEETVIEWS}\r\n{COLS}\r\n{ROWS}\r\n{AUTOFILTER}{MERGECELLS}{HYPERLINKS}{VML}</worksheet>",
  191. 'xl/worksheets/_rels/sheet1.xml.rels' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\r\n"
  192. .'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{RELS}</Relationships>',
  193. 'xl/sharedStrings.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\r\n"
  194. .'<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="{CNT}" uniqueCount="{CNT}">{STRINGS}</sst>',
  195. 'xl/styles.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\r\n"
  196. .'<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
  197. ."\r\n{NUMFMTS}\r\n{FONTS}\r\n{FILLS}\r\n{BORDERS}\r\n"
  198. .'<cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" /></cellStyleXfs>'
  199. ."\r\n{XF}\r\n"
  200. .'<cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0"/></cellStyles></styleSheet>',
  201. 'xl/workbook.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\r\n"
  202. .'<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'."\r\n"
  203. .'<fileVersion appName="{APP}"/><sheets>{SHEETS}</sheets></workbook>',
  204. 'xl/comments1.xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\r\n"
  205. . '<comments' . "\r\n"
  206. . ' xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"' . "\r\n"
  207. . ' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">' . "\r\n"
  208. . '<authors>{AUTHORS}</authors>' . "\r\n"
  209. . '<commentList>{COMMENTS}</commentList>' . "\r\n"
  210. . '</comments>',
  211. 'xl/drawings/vmlDrawing1.vml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\r\n"
  212. . '<xml xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:oa="urn:schemas-microsoft-com:office:activation" xmlns:x="urn:schemas-microsoft-com:office:excel">' . "\r\n"
  213. .'<o:shapelayout v:ext="edit"><o:idmap data="1" v:ext="edit"/></o:shapelayout>' . "\r\n"
  214. .'<v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202.0" path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter"/><v:path o:connecttype="rect" gradientshapeok="t"/></v:shapetype>{SHAPES}</xml>',
  215. '[Content_Types].xml' => '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\r\n"
  216. .'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'."\r\n"
  217. .'<Default Extension="vml" ContentType="application/vnd.openxmlformats-officedocument.vmlDrawing"/>' . "\r\n"
  218. .'<Default Extension="xml" ContentType="application/xml"/>' . "\r\n"
  219. .'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>' . "\r\n"
  220. .'<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>'."\r\n"
  221. .'<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>'."\r\n"
  222. .'<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>'."\r\n"
  223. .'<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>
  224. <Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
  225. ."\r\n{TYPES}</Types>",
  226. ];
  227. }
  228. public static function create($title = null)
  229. {
  230. $xlsx = new static();
  231. if ($title) {
  232. $xlsx->setTitle($title);
  233. }
  234. return $xlsx;
  235. }
  236. public static function fromArray(array $rows, $sheetName = null)
  237. {
  238. $xlsx = new static();
  239. $xlsx->addSheet($rows, $sheetName);
  240. if ($sheetName) {
  241. $xlsx->setTitle($sheetName);
  242. }
  243. return $xlsx;
  244. }
  245. public function addSheet(array $rows, $name = null)
  246. {
  247. $this->curSheet++;
  248. if ($name === null) { // autogenerated sheet names
  249. $name = ($this->title ? mb_substr($this->title, 0, 31) : 'Sheet') . ($this->curSheet + 1);
  250. } else {
  251. $name = mb_substr($name, 0, 31);
  252. $names = [];
  253. foreach ($this->sheets as $sh) {
  254. $names[mb_strtoupper($sh['name'])] = 1;
  255. }
  256. for ($i = 0; $i < 100; $i++) {
  257. $postfix = ' (' . $i . ')';
  258. $new_name = ($i === 0) ? $name : $name . $postfix;
  259. if (mb_strlen($new_name) > 31) {
  260. $new_name = mb_substr($name, 0, 31 - mb_strlen($postfix)) . $postfix;
  261. }
  262. $NEW_NAME = mb_strtoupper($new_name);
  263. if (!isset($names[$NEW_NAME])) {
  264. $name = $new_name;
  265. break;
  266. }
  267. }
  268. }
  269. $this->sheets[$this->curSheet] = ['name' => $name, 'relidx' => 0, 'hyperlinks' => [], 'comments' => [], 'mergecells' => [], 'colwidth' => [], 'autofilter' => '', 'frozen' => ''];
  270. if (isset($rows[0]) && is_array($rows[0])) {
  271. $this->sheets[$this->curSheet]['rows'] = $rows;
  272. } else {
  273. $this->sheets[$this->curSheet]['rows'] = [];
  274. }
  275. return $this;
  276. }
  277. public function __toString()
  278. {
  279. $fh = fopen('php://memory', 'wb');
  280. if (!$fh) {
  281. return '';
  282. }
  283. if (!$this->_write($fh)) {
  284. fclose($fh);
  285. return '';
  286. }
  287. $size = ftell($fh);
  288. fseek($fh, 0);
  289. return (string)fread($fh, $size);
  290. }
  291. public function save()
  292. {
  293. return $this->saveAs(($this->title ?: gmdate('YmdHi')) . '.xlsx');
  294. }
  295. public function saveAs($filename)
  296. {
  297. $fh = fopen(str_replace(["\0","\r","\n","\t",'"'], '', $filename), 'wb');
  298. if (!$fh) {
  299. return false;
  300. }
  301. if (!$this->_write($fh)) {
  302. fclose($fh);
  303. return false;
  304. }
  305. fclose($fh);
  306. return true;
  307. }
  308. public function download()
  309. {
  310. return $this->downloadAs(($this->title ?: gmdate('YmdHi')) . '.xlsx');
  311. }
  312. public function downloadAs($filename)
  313. {
  314. $fh = fopen('php://memory', 'wb');
  315. if (!$fh) {
  316. return false;
  317. }
  318. if (!$this->_write($fh)) {
  319. fclose($fh);
  320. return false;
  321. }
  322. $size = ftell($fh);
  323. header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  324. header('Content-Disposition: attachment; filename="' . str_replace(["\0","\r","\n","\t",'"'], '', $filename) . '"');
  325. header('Last-Modified: ' . gmdate('D, d M Y H:i:s \G\M\T', time()));
  326. header('Content-Length: ' . $size);
  327. while (ob_get_level()) {
  328. ob_end_clean();
  329. }
  330. fseek($fh, 0);
  331. //Some servers disable fpassthru function. The alternative, stream_get_contents, use more memory
  332. if (function_exists('fpassthru')) {
  333. fpassthru($fh);
  334. } else {
  335. echo stream_get_contents($fh);
  336. }
  337. fclose($fh);
  338. return true;
  339. }
  340. protected function _write($fh)
  341. {
  342. $dirSignatureE = "\x50\x4b\x05\x06"; // end of central dir signature
  343. $zipComments = 'Generated by ' . __CLASS__ . ' PHP class, thanks sergey.shuchkin@gmail.com';
  344. if (!$fh) {
  345. return false;
  346. }
  347. $cdrec = ''; // central directory content
  348. $entries = 0; // number of zipped files
  349. $cnt_sheets = count($this->sheets);
  350. if ($cnt_sheets === 0) {
  351. $this->addSheet([], 'No data');
  352. $cnt_sheets = 1;
  353. }
  354. foreach ($this->template as $cfilename => $template) {
  355. if ($cfilename === 'xl/_rels/workbook.xml.rels') {
  356. $s = '';
  357. for ($i = 0; $i < $cnt_sheets; $i++) {
  358. $s .= '<Relationship Id="rId' . ($i + 1) . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"' .
  359. ' Target="worksheets/sheet' . ($i + 1) . ".xml\"/>\r\n";
  360. }
  361. $s .= '<Relationship Id="rId' . ($cnt_sheets + 1) . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>' . "\r\n";
  362. $s .= '<Relationship Id="rId' . ($cnt_sheets + 2) . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>';
  363. $template = str_replace('{RELS}', $s, $template);
  364. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  365. $entries++;
  366. } elseif ($cfilename === 'xl/workbook.xml') {
  367. $s = '';
  368. foreach ($this->sheets as $k => $v) {
  369. $s .= '<sheet name="' . self::esc($v['name']) . '" sheetId="' . ($k + 1) . '" r:id="rId' . ($k + 1) . '"/>';
  370. }
  371. $search = ['{SHEETS}', '{APP}'];
  372. $replace = [$s, self::esc($this->application)];
  373. $template = str_replace($search, $replace, $template);
  374. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  375. $entries++;
  376. } elseif ($cfilename === 'docProps/app.xml') {
  377. $search = ['{APP}', '{COMPANY}', '{MANAGER}'];
  378. $replace = [self::esc($this->application), self::esc($this->company), self::esc($this->manager)];
  379. $template = str_replace($search, $replace, $template);
  380. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  381. $entries++;
  382. } elseif ($cfilename === 'docProps/core.xml') {
  383. $search = ['{DATE}', '{AUTHOR}', '{TITLE}', '{SUBJECT}', '{KEYWORD}', '{DESCRIPTION}', '{CATEGORY}', '{LANGUAGE}', '{LAST_MODIFY_BY}'];
  384. $replace = [gmdate('Y-m-d\TH:i:s\Z'), self::esc($this->author), self::esc($this->title), self::esc($this->subject), self::esc($this->keywords), self::esc($this->description), self::esc($this->category), self::esc($this->language), self::esc($this->lastModifiedBy)];
  385. $template = str_replace($search, $replace, $template);
  386. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  387. $entries++;
  388. } elseif ($cfilename === 'xl/sharedStrings.xml') {
  389. $si_cnt = count($this->SI);
  390. if ($si_cnt) {
  391. $si = [];
  392. foreach ($this->SI as $s) {
  393. $si[] = '<si>' . (preg_match('/^\s|\s$/', $s) ? '<t xml:space="preserve">' . $s . '</t>' : '<t>' . $s . '</t>') . '</si>';
  394. }
  395. $template = str_replace(['{CNT}', '{STRINGS}'], [$si_cnt, implode("\r\n", $si)], $template);
  396. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  397. $entries++;
  398. }
  399. } elseif ($cfilename === 'xl/worksheets/sheet1.xml') {
  400. foreach ($this->sheets as $k => $v) {
  401. $filename = 'xl/worksheets/sheet' . ($k + 1) . '.xml';
  402. $xml = $this->_sheetToXML($k, $template);
  403. $this->_writeEntry($fh, $cdrec, $filename, $xml);
  404. $entries++;
  405. }
  406. $xml = null;
  407. } elseif ($cfilename === 'xl/worksheets/_rels/sheet1.xml.rels') {
  408. foreach ($this->sheets as $k => $v) {
  409. $R = [];
  410. if (count($v['comments'])) {
  411. $this->sheets[$k]['relidx']++;
  412. $R[] = '<Relationship Id="rId' . $this->sheets[$k]['relidx'] . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="../comments' . ($k + 1) . '.xml"/>';
  413. $R[] = '<Relationship Id="rVMLCom" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing" Target="../drawings/vmlDrawing' . ($k + 1) . '.vml"/>';
  414. }
  415. foreach ($v['hyperlinks'] as $h) {
  416. if ($h['ID']) {
  417. $R[] = '<Relationship Id="' . $h['ID'] . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="' . self::esc($h['H']) . '" TargetMode="External"/>';
  418. }
  419. }
  420. if (count($R)) {
  421. $filename = 'xl/worksheets/_rels/sheet' . ($k + 1) . '.xml.rels';
  422. $xml = str_replace('{RELS}', implode("\r\n", $R), $template);
  423. $this->_writeEntry($fh, $cdrec, $filename, $xml);
  424. $entries++;
  425. }
  426. }
  427. $xml = null;
  428. } elseif ($cfilename === 'xl/comments1.xml') {
  429. foreach ($this->sheets as $k => $v) {
  430. $C = [];
  431. $A = [];
  432. foreach ($v['comments'] as $com) {
  433. $A[$com['A']] = count($A);
  434. }
  435. foreach ($v['comments'] as $com) {
  436. $C[] = '<comment ref="' . $com['N'] . '" authorId="' . $A[$com['A']] . '"><text>' . "\r\n"
  437. . ($com['A'] ? ('<r><rPr><b/><sz val="10"/><family val="2"/></rPr><t xml:space="preserve">' . $com['A'] . ":\r\n" .'</t></r>' . "\r\n") : '')
  438. .'<r><rPr><sz val="10"/><family val="2"/></rPr><t xml:space="preserve">' . self::esc($com['T']) . '</t></r>' . "\r\n"
  439. // .'<t xml:space="preserve">' . self::esc($com['T']) . ($com['A'] ? "\r\n\t-" . $com['A'] : '') . '</t>' . "\r\n"
  440. . '</text></comment>';
  441. }
  442. if (count($C)) {
  443. $filename = 'xl/comments' . ($k + 1) . '.xml';
  444. $xml = str_replace(
  445. array('{AUTHORS}', '{COMMENTS}'),
  446. array('<author>' . implode("</author>\r\n<author>", array_keys($A)) . '</author>',
  447. implode("\r\n", $C)), $template
  448. );
  449. $this->_writeEntry($fh, $cdrec, $filename, $xml);
  450. $entries++;
  451. }
  452. }
  453. $xml = null;
  454. } elseif ($cfilename === 'xl/drawings/vmlDrawing1.vml') {
  455. foreach ($this->sheets as $k => $v) {
  456. if (count($v['comments'])) {
  457. $S = [];
  458. foreach ($v['comments'] as $k2 => $com) {
  459. // Anchor: LeftColumn, LeftOffset, TopRow, TopOffset, RightColumn, RightOffset, BottomRow, BottomOffset
  460. $a = [
  461. $com['C'],
  462. 15,
  463. $com['R'],
  464. 10,
  465. $com['C'] + 4,
  466. 15,
  467. $com['R'] + 4,
  468. 4
  469. ];
  470. $S[] = '<v:shape id="_x0000_s' . (1025 + $k2) .'"'
  471. . ' style="visibility:hidden" fillcolor="#ffffe1" type="#_x0000_t202">' . "\r\n"
  472. . ' <v:fill angle="0" color2="#ffffe1"/>' . "\r\n"
  473. . ' <v:shadow color="black" obscured="t" on="t"/>' . "\r\n"
  474. . ' <v:path o:connecttype="none"/><v:textbox/>' . "\r\n"
  475. . ' <x:ClientData ObjectType="Note">' . "\r\n"
  476. . ' <x:MoveWithCells/>' . "\r\n"
  477. . ' <x:SizeWithCells/>' . "\r\n"
  478. . ' <x:Anchor>' . implode(', ', $a) .'</x:Anchor>' . "\r\n"
  479. . ' <x:AutoFill>False</x:AutoFill>' . "\r\n"
  480. . ' <x:Row>' . ($com['R'] - 1) . '</x:Row>' . "\r\n"
  481. . ' <x:Column>' . ($com['C'] - 1) . '</x:Column>' . "\r\n"
  482. . ' </x:ClientData>' . "\r\n"
  483. . '</v:shape>';
  484. }
  485. $filename = 'xl/drawings/vmlDrawing' . ($k + 1) . '.vml';
  486. $xml = str_replace('{SHAPES}', "\r\n" . implode("\r\n", $S) . "\r\n", $template);
  487. $this->_writeEntry($fh, $cdrec, $filename, $xml);
  488. $entries++;
  489. }
  490. }
  491. $xml = null;
  492. } elseif ($cfilename === '[Content_Types].xml') {
  493. $TYPES = [];
  494. foreach ($this->sheets as $k => $v) {
  495. $TYPES[] = '<Override PartName="/xl/worksheets/sheet' . ($k + 1) . '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
  496. if (count($v['comments'])) {
  497. $TYPES[] = '<Override PartName="/xl/comments' . ($k + 1). '.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml" />';
  498. }
  499. }
  500. $template = str_replace('{TYPES}', implode("\r\n", $TYPES), $template);
  501. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  502. $entries++;
  503. } elseif ($cfilename === 'xl/styles.xml') {
  504. $NF = $XF = $FONTS = $F_KEYS = $FILLS = $FL_KEYS = [];
  505. $BR = ['<border><left/><right/><top/><bottom/><diagonal/></border>'];
  506. $BR_KEYS = [0 => 0];
  507. foreach ($this->NF as $k => $v) {
  508. $NF[] = '<numFmt numFmtId="' . $k . '" formatCode="' . htmlspecialchars($v, ENT_QUOTES) . '"/>';
  509. }
  510. foreach ($this->XF as $xf) {
  511. // 0 - num fmt, 1 - align, 2 - font, 3 - fill, 4 - font color, 5 - bgcolor, 6 - border, 7 - font size
  512. // fonts
  513. $F_KEY = $xf[2] . '-' . $xf[4] . '-' . $xf[7];
  514. if (isset($F_KEYS[$F_KEY])) {
  515. $F_ID = $F_KEYS[$F_KEY];
  516. } else {
  517. $F_ID = $F_KEYS[$F_KEY] = count($FONTS);
  518. $FONTS[] = '<font><name val="' . $this->defaultFont . '"/><family val="2"/>'
  519. . ($xf[7] ? '<sz val="' . $xf[7] . '"/>' : '<sz val="' . $this->defaultFontSize . '"/>')
  520. . ($xf[2] & self::F_BOLD ? '<b/>' : '')
  521. . ($xf[2] & self::F_ITALIC ? '<i/>' : '')
  522. . ($xf[2] & self::F_UNDERLINE ? '<u/>' : '')
  523. . ($xf[2] & self::F_STRIKE ? '<strike/>' : '')
  524. . ($xf[2] & self::F_HYPERLINK ? '<u/>' : '')
  525. . ($xf[2] & self::F_COLOR ? '<color rgb="' . $xf[4] . '"/>' : '')
  526. . '</font>';
  527. }
  528. // fills
  529. $FL_KEY = $xf[3] . '-' . $xf[5];
  530. if (isset($FL_KEYS[$FL_KEY])) {
  531. $FL_ID = $FL_KEYS[$FL_KEY];
  532. } else {
  533. $FL_ID = $FL_KEYS[$FL_KEY] = count($FILLS);
  534. $FILLS[] = '<fill><patternFill patternType="'
  535. . ($xf[3] === 0 ? 'none' : '')
  536. . ($xf[3] & self::FL_SOLID ? 'solid' : '')
  537. . ($xf[3] & self::FL_MEDIUM_GRAY ? 'mediumGray' : '')
  538. . ($xf[3] & self::FL_DARK_GRAY ? 'darkGray' : '')
  539. . ($xf[3] & self::FL_LIGHT_GRAY ? 'lightGray' : '')
  540. . ($xf[3] & self::FL_GRAY_125 ? 'gray125' : '')
  541. . '"'
  542. . ($xf[3] & self::FL_COLOR ? '><fgColor rgb="' . $xf[5] . '"/><bgColor indexed="64"/></patternFill>' : ' />')
  543. . '</fill>';
  544. }
  545. $align = '';
  546. if ($xf[1] & self::A_LEFT) {
  547. $align .= ' horizontal="left"';
  548. } elseif ($xf[1] & self::A_RIGHT) {
  549. $align .= ' horizontal="right"';
  550. } elseif ($xf[1] & self::A_CENTER) {
  551. $align .= ' horizontal="center"';
  552. }
  553. if ($xf[1] & self::A_TOP) {
  554. $align .= ' vertical="top"';
  555. } elseif ($xf[1] & self::A_MIDDLE) {
  556. $align .= ' vertical="center"';
  557. } elseif ($xf[1] & self::A_BOTTOM) {
  558. $align .= ' vertical="bottom"';
  559. }
  560. if ($xf[1] & self::A_WRAPTEXT) {
  561. $align .= ' wrapText="1"';
  562. }
  563. // border
  564. $BR_ID = 0;
  565. if ($xf[6] !== '') {
  566. $b = $xf[6];
  567. if (isset($BR_KEYS[$b])) {
  568. $BR_ID = $BR_KEYS[$b];
  569. } else {
  570. $BR_ID = count($BR_KEYS);
  571. $BR_KEYS[$b] = $BR_ID;
  572. $border = '<border>';
  573. $ba = explode(' ', $b);
  574. if (!isset($ba[1])) {
  575. $ba[] = $ba[0];
  576. $ba[] = $ba[0];
  577. $ba[] = $ba[0];
  578. }
  579. if (!isset($ba[4])) { // diagonal
  580. $ba[] = 'none';
  581. }
  582. $sides = ['left' => 3, 'right' => 1, 'top' => 0, 'bottom' => 2, 'diagonal' => 4];
  583. foreach ($sides as $side => $idx) {
  584. $s = 'thin';
  585. $c = '';
  586. $va = explode('#', $ba[$idx]);
  587. if (isset($va[1])) {
  588. $s = $va[0] === '' ? 'thin' : $va[0];
  589. $c = $va[1];
  590. } elseif (in_array($va[0], $this->BR_STYLE, true)) {
  591. $s = $va[0];
  592. } else {
  593. $c = $va[0];
  594. }
  595. if (strlen($c) === 6) {
  596. $c = 'FF' . $c;
  597. }
  598. if ($s && $s !== 'none') {
  599. $border .= '<' . $side . ' style="' . $s . '">'
  600. . '<color ' . ($c === '' ? 'auto="1"' : 'rgb="' . $c . '"') . '/>'
  601. . '</' . $side . '>';
  602. } else {
  603. $border .= '<' . $side . '/>';
  604. }
  605. }
  606. $border .= '</border>';
  607. $BR[] = $border;
  608. }
  609. }
  610. $XF[] = '<xf numFmtId="' . $xf[0] . '" fontId="' . $F_ID . '" fillId="' . $FL_ID . '" borderId="' . $BR_ID . '" xfId="0"'
  611. . ($xf[0] > 0 ? ' applyNumberFormat="1"' : '')
  612. . ($F_ID > 0 ? ' applyFont="1"' : '')
  613. . ($FL_ID > 0 ? ' applyFill="1"' : '')
  614. . ($BR_ID > 0 ? ' applyBorder="1"' : '')
  615. . ($align ? ' applyAlignment="1"><alignment' . $align . '/></xf>' : '/>');
  616. }
  617. // wrap collections
  618. array_unshift($NF, '<numFmts count="' . count($NF) . '">');
  619. $NF[] = '</numFmts>';
  620. array_unshift($XF, '<cellXfs count="' . count($XF) . '">');
  621. $XF[] = '</cellXfs>';
  622. array_unshift($FONTS, '<fonts count="' . count($FONTS) . '">');
  623. $FONTS[] = '</fonts>';
  624. array_unshift($FILLS, '<fills count="' . count($FILLS) . '">');
  625. $FILLS[] = '</fills>';
  626. array_unshift($BR, '<borders count="' . count($BR) . '">');
  627. $BR[] = '</borders>';
  628. $template = str_replace(
  629. ['{NUMFMTS}', '{FONTS}', '{XF}', '{FILLS}', '{BORDERS}'],
  630. [implode("\r\n", $NF), implode("\r\n", $FONTS), implode("\r\n", $XF), implode("\r\n", $FILLS), implode("\r\n", $BR)],
  631. $template
  632. );
  633. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  634. $entries++;
  635. } else {
  636. $this->_writeEntry($fh, $cdrec, $cfilename, $template);
  637. $entries++;
  638. }
  639. }
  640. $before_cd = ftell($fh);
  641. fwrite($fh, $cdrec);
  642. // end of central dir
  643. fwrite($fh, $dirSignatureE);
  644. fwrite($fh, pack('v', 0)); // number of this disk
  645. fwrite($fh, pack('v', 0)); // number of the disk with the start of the central directory
  646. fwrite($fh, pack('v', $entries)); // total # of entries "on this disk"
  647. fwrite($fh, pack('v', $entries)); // total # of entries overall
  648. fwrite($fh, pack('V', mb_strlen($cdrec, '8bit'))); // size of central dir
  649. fwrite($fh, pack('V', $before_cd)); // offset to start of central dir
  650. fwrite($fh, pack('v', mb_strlen($zipComments, '8bit'))); // .zip file comment length
  651. fwrite($fh, $zipComments);
  652. return true;
  653. }
  654. protected function _writeEntry($fh, &$cdrec, $cfilename, $data)
  655. {
  656. $zipSignature = "\x50\x4b\x03\x04"; // local file header signature
  657. $dirSignature = "\x50\x4b\x01\x02"; // central dir header signature
  658. $e = [];
  659. $e['uncsize'] = mb_strlen($data, '8bit');
  660. // if data to compress is too small, just store it
  661. if ($e['uncsize'] < 256) {
  662. $e['comsize'] = $e['uncsize'];
  663. $e['vneeded'] = 10;
  664. $e['cmethod'] = 0;
  665. $zdata = $data;
  666. } else { // otherwise, compress it
  667. $zdata = gzcompress($data);
  668. $zdata = substr(substr($zdata, 0, -4), 2); // fix crc bug (thanks to Eric Mueller)
  669. $e['comsize'] = mb_strlen($zdata, '8bit');
  670. $e['vneeded'] = 10;
  671. $e['cmethod'] = 8;
  672. }
  673. $e['bitflag'] = 0;
  674. $e['crc_32'] = crc32($data);
  675. // Convert date and time to DOS Format, and set then
  676. $date = getdate();
  677. $e['dostime'] = (
  678. (($date['year'] - 1980) << 25)
  679. | ($date['mon'] << 21)
  680. | ($date['mday'] << 16)
  681. | ($date['hours'] << 11)
  682. | ($date['minutes'] << 5)
  683. | ($date['seconds'] >> 1)
  684. );
  685. $e['offset'] = ftell($fh);
  686. fwrite($fh, $zipSignature);
  687. fwrite($fh, pack('v', $e['vneeded'])); // version_needed
  688. fwrite($fh, pack('v', $e['bitflag'])); // general_bit_flag
  689. fwrite($fh, pack('v', $e['cmethod'])); // compression_method
  690. fwrite($fh, pack('V', $e['dostime'])); // lastmod datetime
  691. fwrite($fh, pack('V', $e['crc_32'])); // crc-32
  692. fwrite($fh, pack('V', $e['comsize'])); // compressed_size
  693. fwrite($fh, pack('V', $e['uncsize'])); // uncompressed_size
  694. fwrite($fh, pack('v', mb_strlen($cfilename, '8bit'))); // file_name_length
  695. fwrite($fh, pack('v', 0)); // extra_field_length
  696. fwrite($fh, $cfilename); // file_name
  697. // ignoring extra_field
  698. fwrite($fh, $zdata);
  699. // Append it to central dir
  700. $e['external_attributes'] = (substr($cfilename, -1) === '/' && !$zdata) ? 16 : 32; // Directory or file name
  701. $e['comments'] = '';
  702. $cdrec .= $dirSignature;
  703. $cdrec .= "\x0\x0"; // version made by
  704. $cdrec .= pack('v', $e['vneeded']); // version needed to extract
  705. $cdrec .= "\x0\x0"; // general bit flag
  706. $cdrec .= pack('v', $e['cmethod']); // compression method
  707. $cdrec .= pack('V', $e['dostime']); // lastmod datetime
  708. $cdrec .= pack('V', $e['crc_32']); // crc32
  709. $cdrec .= pack('V', $e['comsize']); // compressed filesize
  710. $cdrec .= pack('V', $e['uncsize']); // uncompressed filesize
  711. $cdrec .= pack('v', mb_strlen($cfilename, '8bit')); // file name length
  712. $cdrec .= pack('v', 0); // extra field length
  713. $cdrec .= pack('v', mb_strlen($e['comments'], '8bit')); // file comment length
  714. $cdrec .= pack('v', 0); // disk number start
  715. $cdrec .= pack('v', 0); // internal file attributes
  716. $cdrec .= pack('V', $e['external_attributes']); // internal file attributes
  717. $cdrec .= pack('V', $e['offset']); // relative offset of local header
  718. $cdrec .= $cfilename;
  719. $cdrec .= $e['comments'];
  720. }
  721. protected function _sheetToXML($idx, $template)
  722. {
  723. // locale floats fr_FR 1.234,56 -> 1234.56
  724. $_loc = setlocale(LC_NUMERIC, 0);
  725. setlocale(LC_NUMERIC, 'C');
  726. $COLS = [];
  727. $ROWS = [];
  728. $VML = [];
  729. // $SHEETVIEWS = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"'.($this->rtl ? ' rightToLeft="1"' : '').'>';
  730. $SHEETVIEWS = '';
  731. $PANE = '';
  732. if (count($this->sheets[$idx]['rows'])) {
  733. $ROWS[] = '<sheetData>';
  734. if ($this->sheets[$idx]['frozen'] !== '' || isset($this->sheets[$idx]['frozen'][0]) || isset($this->sheets[$idx]['frozen'][1])) {
  735. // $AC = 'A1'; // Active Cell
  736. $x = $y = 0;
  737. if (is_string($this->sheets[$idx]['frozen'])) {
  738. $AC = $this->sheets[$idx]['frozen'];
  739. self::cell2coord($AC, $x, $y);
  740. } else {
  741. if (isset($this->sheets[$idx]['frozen'][0])) {
  742. $x = $this->sheets[$idx]['frozen'][0];
  743. }
  744. if (isset($this->sheets[$idx]['frozen'][1])) {
  745. $y = $this->sheets[$idx]['frozen'][1];
  746. }
  747. $AC = self::coord2cell($x, $y);
  748. }
  749. if ($x > 0 || $y > 0) {
  750. $split = '';
  751. if ($x > 0) {
  752. $split .= ' xSplit="' . $x . '"';
  753. }
  754. if ($y > 0) {
  755. $split .= ' ySplit="' . $y . '"';
  756. }
  757. $activepane = 'bottomRight';
  758. if ($x > 0 && $y === 0) {
  759. $activepane = 'topRight';
  760. }
  761. if ($x === 0 && $y > 0) {
  762. $activepane = 'bottomLeft';
  763. }
  764. $PANE .= '<pane' . $split . ' topLeftCell="' . $AC . '" activePane="' . $activepane . '" state="frozen"/>';
  765. $PANE .= '<selection activeCell="' . $AC . '" sqref="' . $AC . '"/>';
  766. }
  767. }
  768. if ($this->rtl || $PANE) {
  769. $SHEETVIEWS .= '<sheetViews>
  770. <sheetView workbookViewId="0"' . ($this->rtl ? ' rightToLeft="1"' : '');
  771. $SHEETVIEWS .= $PANE ? ">\r\n" . $PANE . "\r\n</sheetView>" : ' />';
  772. $SHEETVIEWS .= "\r\n</sheetViews>";
  773. }
  774. $CUR_ROW = 0;
  775. $COL = [];
  776. foreach ($this->sheets[$idx]['rows'] as $r) {
  777. $CUR_ROW++;
  778. $row = '';
  779. $CUR_COL = 0;
  780. $RH = 0; // row height
  781. foreach ($r as $v) {
  782. $CUR_COL++;
  783. if (!isset($COL[$CUR_COL])) {
  784. $COL[$CUR_COL] = 0;
  785. }
  786. $cname = self::coord2cell($CUR_COL-1) . $CUR_ROW;
  787. if ($v === null || $v === '') {
  788. $row .= '<c r="' . $cname . '"/>';
  789. continue;
  790. }
  791. $ct = $cv = $cf = null;
  792. $N = $NF = $A = $F = $FL = $C = $BG = $FS = $FR = 0;
  793. $BR = '';
  794. if (is_string($v)) {
  795. if ($v[0] === "\0") { // RAW value as string
  796. $v = substr($v, 1);
  797. $vl = mb_strlen($v);
  798. } else {
  799. if (strpos($v, '<') !== false) { // tags?
  800. if (preg_match('/<!--(.*?)-->/s', $v, $m)) {
  801. $com = trim($m[1]);
  802. $a = $this->author;
  803. if (preg_match('/^([^:]+): (.*)$/us', $com, $m2)) {
  804. $a = $m2[1];
  805. /** @noinspection MultiAssignmentUsageInspection */
  806. $com = $m2[2];
  807. }
  808. $this->sheets[$idx]['comments'][] = ['C' => $CUR_COL, 'R' => $CUR_ROW, 'N' => $cname, 'T' => $com, 'A' => $a];
  809. $v = str_replace($m[0], '', $v);
  810. }
  811. if (strpos($v, '<b>') !== false) {
  812. $F += self::F_BOLD;
  813. }
  814. if (strpos($v, '<i>') !== false) {
  815. $F += self::F_ITALIC;
  816. }
  817. if (strpos($v, '<u>') !== false) {
  818. $F += self::F_UNDERLINE;
  819. }
  820. if (strpos($v, '<s>') !== false) {
  821. $F += self::F_STRIKE;
  822. }
  823. if (preg_match('/<style([^>]+)>/', $v, $m)) {
  824. if (preg_match('/ color="([^"]+)"/', $m[1], $m2)) {
  825. $F += self::F_COLOR;
  826. $c = ltrim($m2[1], '#');
  827. $C = strlen($c) === 8 ? $c : ('FF' . $c);
  828. }
  829. if (preg_match('/ bgcolor="([^"]+)"/', $m[1], $m2)) {
  830. $FL += self::FL_COLOR;
  831. $c = ltrim($m2[1], '#');
  832. $BG = strlen($c) === 8 ? $c : ('FF' . $c);
  833. }
  834. if (preg_match('/ height="([^"]+)"/', $m[1], $m2)) {
  835. $RH = $m2[1];
  836. }
  837. if (preg_match('/ nf="([^"]+)"/', $m[1], $m2)) {
  838. $c = htmlspecialchars_decode($m2[1], ENT_QUOTES);
  839. $NF = $this->getNumFmtId($c);
  840. }
  841. if (preg_match('/ border="([^"]+)"/', $m[1], $m2)) {
  842. $b = htmlspecialchars_decode($m2[1], ENT_QUOTES);
  843. if ($b && $b !== 'none') {
  844. $BR = $b;
  845. }
  846. }
  847. if (preg_match('/ font-size="([^"]+)"/', $m[1], $m2)) {
  848. $FS = (int)$m2[1];
  849. if ($RH === 0) { // fix row height
  850. $RH = ($FS > $this->defaultFontSize) ? round($FS * 1.50, 1) : 0;
  851. }
  852. }
  853. }
  854. if (strpos($v, '<left>') !== false) {
  855. $A += self::A_LEFT;
  856. }
  857. if (strpos($v, '<center>') !== false) {
  858. $A += self::A_CENTER;
  859. }
  860. if (strpos($v, '<right>') !== false) {
  861. $A += self::A_RIGHT;
  862. }
  863. if (strpos($v, '<top>') !== false) {
  864. $A += self::A_TOP;
  865. }
  866. if (strpos($v, '<middle>') !== false) {
  867. $A += self::A_MIDDLE;
  868. }
  869. if (strpos($v, '<bottom>') !== false) {
  870. $A += self::A_BOTTOM;
  871. }
  872. if (strpos($v, '<wraptext>') !== false) {
  873. $A += self::A_WRAPTEXT;
  874. }
  875. if (preg_match('/<a href="([^"]+)">(.*?)<\/a>/i', $v, $m)) {
  876. $F += self::F_HYPERLINK;
  877. $h = explode('#', $m[1]);
  878. if (count($h) === 1) {
  879. if (strpos($h[0], '!') > 0) { // internal hyperlink
  880. $this->sheets[$idx]['hyperlinks'][] = ['ID' => null, 'R' => $cname, 'H' => null, 'L' => $m[1]];
  881. } else {
  882. $this->sheets[$idx]['relidx']++;
  883. $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->sheets[$idx]['relidx'], 'R' => $cname, 'H' => $m[1], 'L' => ''];
  884. }
  885. } else {
  886. $this->sheets[$idx]['relidx']++;
  887. $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->sheets[$idx]['relidx'], 'R' => $cname, 'H' => $h[0], 'L' => $h[1]];
  888. }
  889. }
  890. // formatted raw?
  891. if (preg_match('/<raw>(.*)<\/raw>/', $v, $m)) {
  892. $FR = 1;
  893. $v = $m[1];
  894. } elseif (preg_match('/<f([^>]*)>/', $v, $m)) {
  895. $cf = strip_tags($v);
  896. $v = 0;
  897. if (preg_match('/ v="([^"]+)"/', $m[1], $m2)) {
  898. $v = $m2[1];
  899. }
  900. } else {
  901. $v = strip_tags($v);
  902. }
  903. } // \tags
  904. $vl = mb_strlen($v);
  905. if ($FR) {
  906. $v = htmlspecialchars_decode($v);
  907. $vl = mb_strlen($v);
  908. } elseif ($N) {
  909. $cv = ltrim($v, '+');
  910. } elseif ($v === '0' || preg_match('/^[-+]?[1-9]\d{0,14}$/', $v)) { // Integer as General
  911. $cv = ltrim($v, '+');
  912. if ($vl > 10) {
  913. $N = self::N_INT; // [1] 0
  914. }
  915. } elseif (preg_match('/^[-+]?(0|[1-9]\d*)\.(\d+)$/', $v, $m)) {
  916. $cv = ltrim($v, '+');
  917. if (strlen($m[2]) < 3) {
  918. $N = self::N_DEC;
  919. }
  920. } elseif (preg_match('/^\$[-+]?[0-9\.]+$/', $v)) { // currency $?
  921. $N = self::N_DOLLAR;
  922. $cv = ltrim($v, '+$');
  923. } elseif (preg_match('/^[-+]?[0-9\.]+( ₽| €)$/u', $v, $m)) { // currency ₽ €?
  924. if ($m[1] === ' ₽') {
  925. $N = self::N_RUB;
  926. } elseif ($m[1] === ' €') {
  927. $N = self::N_EURO;
  928. }
  929. $cv = trim($v, ' +₽€');
  930. } elseif (preg_match('/^([-+]?\d+)%$/', $v, $m)) {
  931. $cv = round($m[1] / 100, 2);
  932. $N = self::N_PERCENT_INT; // [9] 0%
  933. } elseif (preg_match('/^([-+]?\d+\.\d+)%$/', $v, $m)) {
  934. $cv = round($m[1] / 100, 4);
  935. $N = self::N_PRECENT_DEC; // [10] 0.00%
  936. } elseif (preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d)$/', $v, $m)) {
  937. $cv = self::date2excel($m[1], $m[2], $m[3]);
  938. $N = self::N_DATE; // [14] mm-dd-yy
  939. } elseif (preg_match('/^(\d\d)\/(\d\d)\/(\d\d\d\d)$/', $v, $m)) {
  940. $cv = self::date2excel($m[3], $m[2], $m[1]);
  941. $N = self::N_DATE; // [14] mm-dd-yy
  942. } elseif (preg_match('/^(\d\d):(\d\d):(\d\d)$/', $v, $m)) {
  943. $cv = self::date2excel(0, 0, 0, $m[1], $m[2], $m[3]);
  944. $N = self::N_TIME; // time
  945. } elseif (preg_match('/^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$/', $v, $m)) {
  946. $cv = self::date2excel($m[1], $m[2], $m[3], $m[4], $m[5], $m[6]);
  947. $N = ((int)$m[1] === 0) ? self::N_TIME : self::N_DATETIME; // [22] m/d/yy h:mm
  948. } elseif (preg_match('/^(\d\d)\/(\d\d)\/(\d\d\d\d) (\d\d):(\d\d):(\d\d)$/', $v, $m)) {
  949. $cv = self::date2excel($m[3], $m[2], $m[1], $m[4], $m[5], $m[6]);
  950. $N = self::N_DATETIME; // [22] m/d/yy h:mm
  951. } elseif (preg_match('/^[0-9+-.]+$/', $v)) { // Long ?
  952. $A += ($A & (self::A_LEFT | self::A_CENTER)) ? 0 : self::A_RIGHT;
  953. } elseif (preg_match('/^https?:\/\/\S+$/i', $v)) { // Hyperlink ?
  954. $h = explode('#', $v);
  955. $this->sheets[$idx]['relidx']++;
  956. $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->sheets[$idx]['relidx'], 'R' => $cname, 'H' => $h[0], 'L' => isset($h[1]) ? $h[1] : ''];
  957. $F += self::F_HYPERLINK;
  958. } elseif (preg_match("/^[a-zA-Z0-9_\.\-]+@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/", $v)) { // email?
  959. $this->sheets[$idx]['relidx']++;
  960. $this->sheets[$idx]['hyperlinks'][] = ['ID' => 'rId' . $this->sheets[$idx]['relidx'], 'R' => $cname, 'H' => 'mailto:' . $v, 'L' => ''];
  961. $F += self::F_HYPERLINK;
  962. } elseif (strpos($v,"\n") !== false) {
  963. $A |= self::A_WRAPTEXT;
  964. }
  965. if (($N === self::N_DATE || $N === self::N_DATETIME) && $cv < 0) {
  966. $cv = null;
  967. $N = 0;
  968. }
  969. }
  970. if ($cv === null) { // string
  971. $v = self::esc($v);
  972. if ($cf) {
  973. $ct = 'str';
  974. $cv = $v;
  975. } elseif ($v === '') {
  976. $ct = 's';
  977. } elseif (mb_strlen($v) > 160) {
  978. $ct = 'inlineStr';
  979. $cv = $v;
  980. } else {
  981. $ct = 's'; // shared string
  982. $cv = false;
  983. $skey = '~' . $v;
  984. if (isset($this->SI_KEYS[$skey])) {
  985. $cv = $this->SI_KEYS[$skey];
  986. }
  987. if ($cv === false) {
  988. $this->SI[] = $v;
  989. $cv = count($this->SI) - 1;
  990. $this->SI_KEYS[$skey] = $cv;
  991. }
  992. }
  993. }
  994. } elseif (is_int($v)) {
  995. $vl = mb_strlen((string)$v);
  996. $cv = $v;
  997. } elseif (is_float($v)) {
  998. $vl = mb_strlen((string)$v);
  999. $cv = $v;
  1000. } elseif ($v instanceof \DateTime) {
  1001. $vl = 16;
  1002. $cv = self::date2excel($v->format('Y'), $v->format('m'), $v->format('d'), $v->format('H'), $v->format('i'), $v->format('s'));
  1003. $N = self::N_DATETIME; // [22] m/d/yy h:mm
  1004. } else {
  1005. continue;
  1006. }
  1007. if ($NF) {
  1008. $N = $NF;
  1009. }
  1010. $COL[$CUR_COL] = max($vl, $COL[$CUR_COL]);
  1011. $cs = 0;
  1012. if (($N + $A + $F + $FL + $FS > 0) || $BR !== '') {
  1013. if ($FL === self::FL_COLOR) {
  1014. $FL += self::FL_SOLID;
  1015. }
  1016. if (($F & self::F_HYPERLINK) && !($F & self::F_COLOR)) {
  1017. $F += self::F_COLOR;
  1018. $C = 'FF0563C1';
  1019. }
  1020. $XF_KEY = $N . '-' . $A . '-' . $F . '-' . $FL . '-' . $C . '-' . $BG . '-' . $BR . '-' . $FS;
  1021. if (isset($this->XF_KEYS[$XF_KEY])) {
  1022. $cs = $this->XF_KEYS[$XF_KEY];
  1023. }
  1024. if ($cs === 0) {
  1025. $cs = count($this->XF);
  1026. $this->XF_KEYS[$XF_KEY] = $cs;
  1027. $this->XF[] = [$N, $A, $F, $FL, $C, $BG, $BR, $FS];
  1028. }
  1029. }
  1030. $row .= '<c r="' . $cname . '"' . ($ct ? ' t="' . $ct . '"' : '') . ($cs ? ' s="' . $cs . '"' : '');
  1031. if ($ct === 's' && $cv === null) {
  1032. $row .= '/>';
  1033. } else {
  1034. $row .= '>'
  1035. . ($cf ? '<f>' . $cf . '</f>' : '')
  1036. . ($ct === 'inlineStr' ? '<is><t>' . $cv . '</t></is>' : '<v>' . $cv . '</v>')
  1037. . "</c>\r\n";
  1038. }
  1039. }
  1040. $ROWS[] = '<row r="' . $CUR_ROW . '"' . ($RH ? ' customHeight="1" ht="' . $RH . '"' : '') . '>' . $row . "</row>";
  1041. }
  1042. $COLS[] = '<cols>';
  1043. foreach ($COL as $k => $max) {
  1044. if ($max === 0) {
  1045. continue;
  1046. }
  1047. $w = isset($this->sheets[$idx]['colwidth'][$k]) ? $this->sheets[$idx]['colwidth'][$k] : min($max + 1, 60);
  1048. $COLS[] = '<col min="' . $k . '" max="' . $k . '" width="' . $w . '" customWidth="1" />';
  1049. }
  1050. $COLS[] = '</cols>';
  1051. if (count($COLS) === 2) {
  1052. $COLS = [];
  1053. }
  1054. $ROWS[] = '</sheetData>';
  1055. $REF = 'A1:' . self::coord2cell(count($COL)-1) . $CUR_ROW;
  1056. } else {
  1057. $ROWS[] = '<sheetData/>';
  1058. $REF = 'A1:A1';
  1059. }
  1060. $AUTOFILTER = '';
  1061. if ($this->sheets[$idx]['autofilter']) {
  1062. $AUTOFILTER = '<autoFilter ref="' . $this->sheets[$idx]['autofilter'] . '" />';
  1063. }
  1064. $MERGECELLS = [];
  1065. if (count($this->sheets[$idx]['mergecells'])) {
  1066. $MERGECELLS[] = '';
  1067. $MERGECELLS[] = '<mergeCells count="' . count($this->sheets[$idx]['mergecells']) . '">';
  1068. foreach ($this->sheets[$idx]['mergecells'] as $m) {
  1069. $MERGECELLS[] = '<mergeCell ref="' . $m . '"/>';
  1070. }
  1071. $MERGECELLS[] = '</mergeCells>';
  1072. }
  1073. $HYPERLINKS = [];
  1074. if (count($this->sheets[$idx]['hyperlinks'])) {
  1075. $HYPERLINKS[] = '<hyperlinks>';
  1076. foreach ($this->sheets[$idx]['hyperlinks'] as $h) {
  1077. $HYPERLINKS[] = '<hyperlink ref="' . $h['R'] . '"' . ($h['ID'] ? ' r:id="' . $h['ID'] . '"' : '') . ' location="' . self::esc($h['L']) . '" display="' . self::esc($h['H'] . ($h['L'] ? ' - ' . $h['L'] : '')) . '" />';
  1078. }
  1079. $HYPERLINKS[] = '</hyperlinks>';
  1080. }
  1081. if (count($this->sheets[$idx]['comments'])) {
  1082. $VML[] = '<legacyDrawing r:id="rVMLCom" />';
  1083. }
  1084. //restore locale
  1085. setlocale(LC_NUMERIC, $_loc);
  1086. return str_replace(
  1087. ['{REF}', '{COLS}', '{ROWS}', '{AUTOFILTER}', '{MERGECELLS}', '{HYPERLINKS}', '{SHEETVIEWS}', '{VML}'],
  1088. [
  1089. $REF,
  1090. implode("\r\n", $COLS),
  1091. implode("\r\n", $ROWS),
  1092. $AUTOFILTER,
  1093. implode("\r\n", $MERGECELLS),
  1094. implode("\r\n", $HYPERLINKS),
  1095. $SHEETVIEWS,
  1096. implode("\r\n", $VML)
  1097. ],
  1098. $template
  1099. );
  1100. }
  1101. public function setDefaultFont($name)
  1102. {
  1103. $this->defaultFont = $name;
  1104. return $this;
  1105. }
  1106. public function setDefaultFontSize($size)
  1107. {
  1108. $this->defaultFontSize = $size;
  1109. return $this;
  1110. }
  1111. public function setTitle($title)
  1112. {
  1113. $this->title = $title;
  1114. return $this;
  1115. }
  1116. public function setSubject($subject)
  1117. {
  1118. $this->subject = $subject;
  1119. return $this;
  1120. }
  1121. public function setAuthor($author)
  1122. {
  1123. $this->author = $author;
  1124. return $this;
  1125. }
  1126. public function setCompany($company)
  1127. {
  1128. $this->company = $company;
  1129. return $this;
  1130. }
  1131. public function setManager($manager)
  1132. {
  1133. $this->manager = $manager;
  1134. return $this;
  1135. }
  1136. public function setKeywords($keywords)
  1137. {
  1138. $this->keywords = $keywords;
  1139. return $this;
  1140. }
  1141. public function setDescription($description)
  1142. {
  1143. $this->description = $description;
  1144. return $this;
  1145. }
  1146. public function setCategory($category)
  1147. {
  1148. $this->category = $category;
  1149. return $this;
  1150. }
  1151. public function setLanguage($language)
  1152. {
  1153. $this->language = $language;
  1154. return $this;
  1155. }
  1156. public function setApplication($application)
  1157. {
  1158. $this->application = $application;
  1159. return $this;
  1160. }
  1161. public function setLastModifiedBy($lastModifiedBy)
  1162. {
  1163. $this->lastModifiedBy = $lastModifiedBy;
  1164. return $this;
  1165. }
  1166. /**
  1167. * @param $range string 'A2:B10'
  1168. * @return $this
  1169. */
  1170. public function autoFilter($range)
  1171. {
  1172. $this->sheets[$this->curSheet]['autofilter'] = $range;
  1173. return $this;
  1174. }
  1175. public function mergeCells($range)
  1176. {
  1177. $this->sheets[$this->curSheet]['mergecells'][] = $range;
  1178. return $this;
  1179. }
  1180. public function setColWidth($col, $width)
  1181. {
  1182. $this->sheets[$this->curSheet]['colwidth'][$col] = $width;
  1183. return $this;
  1184. }
  1185. public function rightToLeft($value = true)
  1186. {
  1187. $this->rtl = $value;
  1188. return $this;
  1189. }
  1190. public function freezePanes($cell)
  1191. {
  1192. $this->sheets[$this->curSheet]['frozen'] = $cell;
  1193. return $this;
  1194. }
  1195. public function getNumFmtId($code)
  1196. {
  1197. if (isset($this->NF[$code])) { // id?
  1198. return (int)$code;
  1199. }
  1200. if (isset($this->NF_KEYS[$code])) {
  1201. return $this->NF_KEYS[$code];
  1202. }
  1203. $id = self::N_CUSTOM + count($this->NF); // custom
  1204. $this->NF[$id] = $code;
  1205. $this->NF_KEYS[$code] = $id;
  1206. return $id;
  1207. }
  1208. public static function date2excel($year, $month, $day, $hours = 0, $minutes = 0, $seconds = 0)
  1209. {
  1210. $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400;
  1211. $year = (int) $year;
  1212. $month = (int) $month;
  1213. $day = (int) $day;
  1214. // echo "y=$year m=$month d=$day h=$hours m=$minutes s=$seconds".PHP_EOL;
  1215. if ($year === 0) {
  1216. return $excelTime;
  1217. }
  1218. // self::CALENDAR_WINDOWS_1900
  1219. $excel1900isLeapYear = 1;
  1220. if (($year === 1900) && ($month <= 2)) {
  1221. $excel1900isLeapYear = 0;
  1222. }
  1223. $myExcelBaseDate = 2415020;
  1224. // Julian base date Adjustment
  1225. if ($month > 2) {
  1226. $month -= 3;
  1227. } else {
  1228. $month += 9;
  1229. --$year;
  1230. }
  1231. $century = floor($year / 100);
  1232. $decade = $year - floor($year / 100) * 100;
  1233. // echo "y=$year m=$month d=$day cent=$century dec=$decade h=$hours m=$minutes s=$seconds".PHP_EOL;
  1234. // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0)
  1235. $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myExcelBaseDate + $excel1900isLeapYear;
  1236. return (float)$excelDate + $excelTime;
  1237. }
  1238. public static function esc($str)
  1239. {
  1240. // XML UTF-8: #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
  1241. // but we use fast version
  1242. return str_replace(['&', '<', '>', "\x00", "\x03", "\x0B"], ['&amp;', '&lt;', '&gt;', '', '', ''], $str);
  1243. }
  1244. public static function raw($value)
  1245. {
  1246. return "\0" . $value;
  1247. }
  1248. public static function rawArray($array)
  1249. {
  1250. foreach ($array as &$row) {
  1251. foreach ($row as &$value) {
  1252. $value = "\0" . $value;
  1253. }
  1254. }
  1255. return $array;
  1256. }
  1257. public static function cell2coord($cell, &$x, &$y)
  1258. {
  1259. $x = $y = 0;
  1260. if (preg_match('/^([A-Z]+)(\d+)$/', $cell, $m)) {
  1261. $len = strlen($m[1]);
  1262. for ($i = 0; $i < $len; $i++) {
  1263. $int = ord($m[1][$i]) - 65; // A -> 0, B -> 1
  1264. $int += ($i === $len - 1) ? 0 : 1;
  1265. $x += $int * pow(26, $len-$i-1);
  1266. }
  1267. $y = ((int)$m[2]) - 1;
  1268. }
  1269. }
  1270. public static function coord2cell($x, $y = null)
  1271. {
  1272. $c = '';
  1273. for ($i = $x; $i >= 0; $i = ((int)($i / 26)) - 1) {
  1274. $c = chr(65 + $i % 26) . $c;
  1275. }
  1276. return $c . ($y === null ? '' : ($y + 1));
  1277. }
  1278. }