暂无描述

XLSXWriter.php 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. <?php
  2. namespace MailPoetVendor;
  3. if (!defined('ABSPATH')) exit;
  4. /*
  5. * @license MIT License
  6. * */
  7. if (!class_exists('ZipArchive')) { throw new \Exception('ZipArchive not found');
  8. }
  9. class XLSXWriter
  10. {
  11. //------------------------------------------------------------------
  12. //http://office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP010073849.aspx
  13. const EXCEL_2007_MAX_ROW = 1048576;
  14. const EXCEL_2007_MAX_COL = 16384;
  15. //------------------------------------------------------------------
  16. protected $author = 'MailPoet';
  17. protected $sheets = [];
  18. protected $shared_strings = [];//unique set
  19. protected $shared_string_count = 0;//count of non-unique references to the unique set
  20. protected $temp_files = [];
  21. protected $current_sheet = '';
  22. public $rtl = false;
  23. public function __construct() {
  24. if (!ini_get('date.timezone'))
  25. {
  26. //using date functions can kick out warning if this isn't set
  27. date_default_timezone_set('UTC');
  28. }
  29. }
  30. public function setAuthor($author='') {
  31. $this->author = $author;
  32. }
  33. public function __destruct() {
  34. if (!empty($this->temp_files)) {
  35. foreach ($this->temp_files as $temp_file) {
  36. @unlink($temp_file);
  37. }
  38. }
  39. }
  40. protected function tempFilename() {
  41. $filename = tempnam(sys_get_temp_dir(), "xlsx_writer_");
  42. $this->temp_files[] = $filename;
  43. return $filename;
  44. }
  45. public function writeToStdOut() {
  46. $temp_file = $this->tempFilename();
  47. self::writeToFile($temp_file);
  48. readfile($temp_file);
  49. }
  50. public function writeToString() {
  51. $temp_file = $this->tempFilename();
  52. self::writeToFile($temp_file);
  53. $string = file_get_contents($temp_file);
  54. return $string;
  55. }
  56. public function writeToFile($filename) {
  57. foreach ($this->sheets as $sheet_name => $sheet) {
  58. self::finalizeSheet($sheet_name);//making sure all footers have been written
  59. }
  60. @unlink($filename);//if the zip already exists, overwrite it
  61. $zip = new \ZipArchive();
  62. if (empty($this->sheets)) { self::log("Error in " . __CLASS__ . "::" . __FUNCTION__ . ", no worksheets defined.");
  63. return;
  64. }
  65. if (!$zip->open($filename, \ZipArchive::CREATE)) { self::log("Error in " . __CLASS__ . "::" . __FUNCTION__ . ", unable to create zip.");
  66. return;
  67. }
  68. $zip->addEmptyDir("docProps/");
  69. $zip->addFromString("docProps/app.xml", self::buildAppXML() );
  70. $zip->addFromString("docProps/core.xml", self::buildCoreXML());
  71. $zip->addEmptyDir("_rels/");
  72. $zip->addFromString("_rels/.rels", self::buildRelationshipsXML());
  73. $zip->addEmptyDir("xl/worksheets/");
  74. foreach ($this->sheets as $sheet) {
  75. $zip->addFile($sheet->filename, "xl/worksheets/" . $sheet->xmlname );
  76. }
  77. if (!empty($this->shared_strings)) {
  78. $zip->addFile($this->writeSharedStringsXML(), "xl/sharedStrings.xml" ); //$zip->addFromString("xl/sharedStrings.xml", self::buildSharedStringsXML() );
  79. }
  80. $zip->addFromString("xl/workbook.xml", self::buildWorkbookXML() );
  81. $zip->addFile($this->writeStylesXML(), "xl/styles.xml" ); //$zip->addFromString("xl/styles.xml" , self::buildStylesXML() );
  82. $zip->addFromString("[Content_Types].xml", self::buildContentTypesXML() );
  83. $zip->addEmptyDir("xl/_rels/");
  84. $zip->addFromString("xl/_rels/workbook.xml.rels", self::buildWorkbookRelsXML() );
  85. $zip->close();
  86. }
  87. protected function initializeSheet($sheet_name) {
  88. //if already initialized
  89. if ($this->current_sheet == $sheet_name || isset($this->sheets[$sheet_name]))
  90. return;
  91. $sheet_filename = $this->tempFilename();
  92. $sheet_xmlname = 'sheet' . (count($this->sheets) + 1) . ".xml";
  93. $this->sheets[$sheet_name] = (object)[
  94. 'filename' => $sheet_filename,
  95. 'sheetname' => $sheet_name,
  96. 'xmlname' => $sheet_xmlname,
  97. 'row_count' => 0,
  98. 'file_writer' => new XLSXWriter_BuffererWriter($sheet_filename),
  99. 'cell_formats' => [],
  100. 'max_cell_tag_start' => 0,
  101. 'max_cell_tag_end' => 0,
  102. 'finalized' => false,
  103. ];
  104. $sheet = &$this->sheets[$sheet_name];
  105. $tabselected = count($this->sheets) == 1 ? 'true' : 'false';//only first sheet is selected
  106. $max_cell = XLSXWriter::xlsCell(self::EXCEL_2007_MAX_ROW, self::EXCEL_2007_MAX_COL);//XFE1048577
  107. $sheet->file_writer->write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n");
  108. $sheet->file_writer->write('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">');
  109. $sheet->file_writer->write( '<sheetPr filterMode="false">');
  110. $sheet->file_writer->write( '<pageSetUpPr fitToPage="false"/>');
  111. $sheet->file_writer->write( '</sheetPr>');
  112. $sheet->max_cell_tag_start = $sheet->file_writer->ftell();
  113. $sheet->file_writer->write('<dimension ref="A1:' . $max_cell . '"/>');
  114. $sheet->max_cell_tag_end = $sheet->file_writer->ftell();
  115. $sheet->file_writer->write( '<sheetViews>');
  116. $sheet->file_writer->write( '<sheetView colorId="64" defaultGridColor="true" rightToLeft="' . $this->rtl . '" showFormulas="false" showGridLines="true" showOutlineSymbols="true" showRowColHeaders="true" showZeros="true" tabSelected="' . $tabselected . '" topLeftCell="A1" view="normal" windowProtection="false" workbookViewId="0" zoomScale="100" zoomScaleNormal="100" zoomScalePageLayoutView="100">');
  117. $sheet->file_writer->write( '<selection activeCell="A1" activeCellId="0" pane="topLeft" sqref="A1"/>');
  118. $sheet->file_writer->write( '</sheetView>');
  119. $sheet->file_writer->write( '</sheetViews>');
  120. $sheet->file_writer->write( '<cols>');
  121. $sheet->file_writer->write( '<col collapsed="false" hidden="false" max="1025" min="1" style="0" width="11.5"/>');
  122. $sheet->file_writer->write( '</cols>');
  123. $sheet->file_writer->write( '<sheetData>');
  124. }
  125. public function writeSheetHeader($sheet_name, array $header_types) {
  126. if (empty($sheet_name) || empty($header_types) || !empty($this->sheets[$sheet_name]))
  127. return;
  128. self::initializeSheet($sheet_name);
  129. $sheet = &$this->sheets[$sheet_name];
  130. $sheet->cell_formats = array_values($header_types);
  131. $header_row = array_keys($header_types);
  132. $sheet->file_writer->write('<row collapsed="false" customFormat="false" customHeight="false" hidden="false" ht="12.1" outlineLevel="0" r="' . (1) . '">');
  133. foreach ($header_row as $k => $v) {
  134. $this->writeCell($sheet->file_writer, 0, $k, $v, $cell_format = 'string');
  135. }
  136. $sheet->file_writer->write('</row>');
  137. $sheet->row_count++;
  138. $this->current_sheet = $sheet_name;
  139. }
  140. public function writeSheetRow($sheet_name, array $row) {
  141. if (empty($sheet_name) || empty($row))
  142. return;
  143. self::initializeSheet($sheet_name);
  144. $sheet = &$this->sheets[$sheet_name];
  145. if (empty($sheet->cell_formats))
  146. {
  147. $sheet->cell_formats = array_fill(0, count($row), 'string');
  148. }
  149. $sheet->file_writer->write('<row collapsed="false" customFormat="false" customHeight="false" hidden="false" ht="12.1" outlineLevel="0" r="' . ($sheet->row_count + 1) . '">');
  150. foreach ($row as $k => $v) {
  151. $this->writeCell($sheet->file_writer, $sheet->row_count, $k, $v, $sheet->cell_formats[$k]);
  152. }
  153. $sheet->file_writer->write('</row>');
  154. $sheet->row_count++;
  155. $this->current_sheet = $sheet_name;
  156. }
  157. protected function finalizeSheet($sheet_name) {
  158. if (empty($sheet_name) || $this->sheets[$sheet_name]->finalized)
  159. return;
  160. $sheet = &$this->sheets[$sheet_name];
  161. $sheet->file_writer->write( '</sheetData>');
  162. $sheet->file_writer->write( '<printOptions headings="false" gridLines="false" gridLinesSet="true" horizontalCentered="false" verticalCentered="false"/>');
  163. $sheet->file_writer->write( '<pageMargins left="0.5" right="0.5" top="1.0" bottom="1.0" header="0.5" footer="0.5"/>');
  164. $sheet->file_writer->write( '<pageSetup blackAndWhite="false" cellComments="none" copies="1" draft="false" firstPageNumber="1" fitToHeight="1" fitToWidth="1" horizontalDpi="300" orientation="portrait" pageOrder="downThenOver" paperSize="1" scale="100" useFirstPageNumber="true" usePrinterDefaults="false" verticalDpi="300"/>');
  165. $sheet->file_writer->write( '<headerFooter differentFirst="false" differentOddEven="false">');
  166. $sheet->file_writer->write( '<oddHeader>&amp;C&amp;&quot;Times New Roman,Regular&quot;&amp;12&amp;A</oddHeader>');
  167. $sheet->file_writer->write( '<oddFooter>&amp;C&amp;&quot;Times New Roman,Regular&quot;&amp;12Page &amp;P</oddFooter>');
  168. $sheet->file_writer->write( '</headerFooter>');
  169. $sheet->file_writer->write('</worksheet>');
  170. $max_cell = self::xlsCell($sheet->row_count - 1, count($sheet->cell_formats) - 1);
  171. $max_cell_tag = '<dimension ref="A1:' . $max_cell . '"/>';
  172. $padding_length = $sheet->max_cell_tag_end - $sheet->max_cell_tag_start - strlen($max_cell_tag);
  173. $sheet->file_writer->fseek($sheet->max_cell_tag_start);
  174. $sheet->file_writer->write($max_cell_tag . str_repeat(" ", (int)$padding_length));
  175. $sheet->file_writer->close();
  176. $sheet->finalized = true;
  177. }
  178. public function writeSheet(array $data, $sheet_name='', array $header_types=[] ) {
  179. $sheet_name = empty($sheet_name) ? 'Sheet1' : $sheet_name;
  180. $data = empty($data) ? [['']] : $data;
  181. if (!empty($header_types))
  182. {
  183. $this->writeSheetHeader($sheet_name, $header_types);
  184. }
  185. foreach ($data as $i => $row)
  186. {
  187. $this->writeSheetRow($sheet_name, $row);
  188. }
  189. $this->finalizeSheet($sheet_name);
  190. }
  191. protected function writeCell(XLSXWriter_BuffererWriter &$file, $row_number, $column_number, $value, $cell_format) {
  192. static $styles = ['money' => 1,'dollar' => 1,'datetime' => 2,'date' => 3,'string' => 0];
  193. $cell = self::xlsCell($row_number, $column_number);
  194. $s = isset($styles[$cell_format]) ? $styles[$cell_format] : '0';
  195. if (!is_scalar($value) || $value == '') { //objects, array, empty
  196. $file->write('<c r="' . $cell . '" s="' . $s . '"/>');
  197. } elseif ($cell_format == 'date') {
  198. $file->write('<c r="' . $cell . '" s="' . $s . '" t="n"><v>' . intval(self::convert_date_time($value)) . '</v></c>');
  199. } elseif ($cell_format == 'datetime') {
  200. $file->write('<c r="' . $cell . '" s="' . $s . '" t="n"><v>' . self::convert_date_time($value) . '</v></c>');
  201. } elseif (!is_string($value)) {
  202. $file->write('<c r="' . $cell . '" s="' . $s . '" t="n"><v>' . ($value * 1) . '</v></c>');//int,float, etc
  203. } elseif ($value[0] != '0' && filter_var($value, FILTER_VALIDATE_INT)){ //excel wants to trim leading zeros
  204. $file->write('<c r="' . $cell . '" s="' . $s . '" t="n"><v>' . ($value) . '</v></c>');//numeric string
  205. } elseif ($value[0] == '='){
  206. $file->write('<c r="' . $cell . '" s="' . $s . '" t="s"><f>' . self::xmlspecialchars($value) . '</f></c>');
  207. } elseif ($value !== ''){
  208. $file->write('<c r="' . $cell . '" s="' . $s . '" t="s"><v>' . self::xmlspecialchars($this->setSharedString($value)) . '</v></c>');
  209. }
  210. }
  211. protected function writeStylesXML() {
  212. $temporary_filename = $this->tempFilename();
  213. $file = new XLSXWriter_BuffererWriter($temporary_filename);
  214. $file->write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n");
  215. $file->write('<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">');
  216. $file->write('<numFmts count="4">');
  217. $file->write( '<numFmt formatCode="GENERAL" numFmtId="164"/>');
  218. $file->write( '<numFmt formatCode="[$$-1009]#,##0.00;[RED]\-[$$-1009]#,##0.00" numFmtId="165"/>');
  219. $file->write( '<numFmt formatCode="YYYY-MM-DD\ HH:MM:SS" numFmtId="166"/>');
  220. $file->write( '<numFmt formatCode="YYYY-MM-DD" numFmtId="167"/>');
  221. $file->write('</numFmts>');
  222. $file->write('<fonts count="4">');
  223. $file->write( '<font><name val="Arial"/><charset val="1"/><family val="2"/><sz val="10"/></font>');
  224. $file->write( '<font><name val="Arial"/><family val="0"/><sz val="10"/></font>');
  225. $file->write( '<font><name val="Arial"/><family val="0"/><sz val="10"/></font>');
  226. $file->write( '<font><name val="Arial"/><family val="0"/><sz val="10"/></font>');
  227. $file->write('</fonts>');
  228. $file->write('<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>');
  229. $file->write('<borders count="1"><border diagonalDown="false" diagonalUp="false"><left/><right/><top/><bottom/><diagonal/></border></borders>');
  230. $file->write( '<cellStyleXfs count="20">');
  231. $file->write( '<xf applyAlignment="true" applyBorder="true" applyFont="true" applyProtection="true" borderId="0" fillId="0" fontId="0" numFmtId="164">');
  232. $file->write( '<alignment horizontal="general" indent="0" shrinkToFit="false" textRotation="0" vertical="bottom" wrapText="false"/>');
  233. $file->write( '<protection hidden="false" locked="true"/>');
  234. $file->write( '</xf>');
  235. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="0"/>');
  236. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="0"/>');
  237. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="2" numFmtId="0"/>');
  238. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="2" numFmtId="0"/>');
  239. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  240. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  241. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  242. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  243. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  244. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  245. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  246. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  247. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  248. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  249. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="43"/>');
  250. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="41"/>');
  251. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="44"/>');
  252. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="42"/>');
  253. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="9"/>');
  254. $file->write( '</cellStyleXfs>');
  255. $file->write( '<cellXfs count="4">');
  256. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="164" xfId="0"/>');
  257. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="165" xfId="0"/>');
  258. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="166" xfId="0"/>');
  259. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="167" xfId="0"/>');
  260. $file->write( '</cellXfs>');
  261. $file->write( '<cellStyles count="6">');
  262. $file->write( '<cellStyle builtinId="0" customBuiltin="false" name="Normal" xfId="0"/>');
  263. $file->write( '<cellStyle builtinId="3" customBuiltin="false" name="Comma" xfId="15"/>');
  264. $file->write( '<cellStyle builtinId="6" customBuiltin="false" name="Comma [0]" xfId="16"/>');
  265. $file->write( '<cellStyle builtinId="4" customBuiltin="false" name="Currency" xfId="17"/>');
  266. $file->write( '<cellStyle builtinId="7" customBuiltin="false" name="Currency [0]" xfId="18"/>');
  267. $file->write( '<cellStyle builtinId="5" customBuiltin="false" name="Percent" xfId="19"/>');
  268. $file->write( '</cellStyles>');
  269. $file->write('</styleSheet>');
  270. $file->close();
  271. return $temporary_filename;
  272. }
  273. protected function setSharedString($v) {
  274. if (isset($this->shared_strings[$v]))
  275. {
  276. $string_value = $this->shared_strings[$v];
  277. }
  278. else
  279. {
  280. $string_value = count($this->shared_strings);
  281. $this->shared_strings[$v] = $string_value;
  282. }
  283. $this->shared_string_count++;//non-unique count
  284. return $string_value;
  285. }
  286. protected function writeSharedStringsXML() {
  287. $temporary_filename = $this->tempFilename();
  288. $file = new XLSXWriter_BuffererWriter($temporary_filename, $fd_flags = 'w', $check_utf8 = true);
  289. $file->write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n");
  290. $file->write('<sst count="' . ($this->shared_string_count) . '" uniqueCount="' . count($this->shared_strings) . '" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">');
  291. foreach ($this->shared_strings as $s => $c)
  292. {
  293. $file->write('<si><t>' . self::xmlspecialchars($s) . '</t></si>');
  294. }
  295. $file->write('</sst>');
  296. $file->close();
  297. return $temporary_filename;
  298. }
  299. protected function buildAppXML() {
  300. $app_xml = "";
  301. $app_xml .= '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n";
  302. $app_xml .= '<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"><TotalTime>0</TotalTime></Properties>';
  303. return $app_xml;
  304. }
  305. protected function buildCoreXML() {
  306. $core_xml = "";
  307. $core_xml .= '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n";
  308. $core_xml .= '<cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcmitype="http://purl.org/dc/dcmitype/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">';
  309. $core_xml .= '<dcterms:created xsi:type="dcterms:W3CDTF">' . date("Y-m-d\TH:i:s.00\Z") . '</dcterms:created>';//$date_time = '2014-10-25T15:54:37.00Z';
  310. $core_xml .= '<dc:creator>' . self::xmlspecialchars($this->author) . '</dc:creator>';
  311. $core_xml .= '<cp:revision>0</cp:revision>';
  312. $core_xml .= '</cp:coreProperties>';
  313. return $core_xml;
  314. }
  315. protected function buildRelationshipsXML() {
  316. $rels_xml = "";
  317. $rels_xml .= '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
  318. $rels_xml .= '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">';
  319. $rels_xml .= '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>';
  320. $rels_xml .= '<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>';
  321. $rels_xml .= '<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>';
  322. $rels_xml .= "\n";
  323. $rels_xml .= '</Relationships>';
  324. return $rels_xml;
  325. }
  326. protected function buildWorkbookXML() {
  327. $i = 0;
  328. $workbook_xml = "";
  329. $workbook_xml .= '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n";
  330. $workbook_xml .= '<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">';
  331. $workbook_xml .= '<fileVersion appName="Calc"/><workbookPr backupFile="false" showObjects="all" date1904="false"/><workbookProtection/>';
  332. $workbook_xml .= '<bookViews><workbookView activeTab="0" firstSheet="0" showHorizontalScroll="true" showSheetTabs="true" showVerticalScroll="true" tabRatio="212" windowHeight="8192" windowWidth="16384" xWindow="0" yWindow="0"/></bookViews>';
  333. $workbook_xml .= '<sheets>';
  334. foreach ($this->sheets as $sheet_name => $sheet) {
  335. $workbook_xml .= '<sheet name="' . self::xmlspecialchars($sheet->sheetname) . '" sheetId="' . ($i + 1) . '" state="visible" r:id="rId' . ($i + 2) . '"/>';
  336. $i++;
  337. }
  338. $workbook_xml .= '</sheets>';
  339. $workbook_xml .= '<calcPr iterateCount="100" refMode="A1" iterate="false" iterateDelta="0.001"/></workbook>';
  340. return $workbook_xml;
  341. }
  342. protected function buildWorkbookRelsXML() {
  343. $i = 0;
  344. $wkbkrels_xml = "";
  345. $wkbkrels_xml .= '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
  346. $wkbkrels_xml .= '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">';
  347. $wkbkrels_xml .= '<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>';
  348. foreach ($this->sheets as $sheet_name => $sheet) {
  349. $wkbkrels_xml .= '<Relationship Id="rId' . ($i + 2) . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/' . ($sheet->xmlname) . '"/>';
  350. $i++;
  351. }
  352. if (!empty($this->shared_strings)) {
  353. $wkbkrels_xml .= '<Relationship Id="rId' . (count($this->sheets) + 2) . '" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>';
  354. }
  355. $wkbkrels_xml .= "\n";
  356. $wkbkrels_xml .= '</Relationships>';
  357. return $wkbkrels_xml;
  358. }
  359. protected function buildContentTypesXML() {
  360. $content_types_xml = "";
  361. $content_types_xml .= '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
  362. $content_types_xml .= '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">';
  363. $content_types_xml .= '<Override PartName="/_rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
  364. $content_types_xml .= '<Override PartName="/xl/_rels/workbook.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
  365. foreach ($this->sheets as $sheet_name => $sheet) {
  366. $content_types_xml .= '<Override PartName="/xl/worksheets/' . ($sheet->xmlname) . '" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
  367. }
  368. if (!empty($this->shared_strings)) {
  369. $content_types_xml .= '<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>';
  370. }
  371. $content_types_xml .= '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>';
  372. $content_types_xml .= '<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>';
  373. $content_types_xml .= '<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>';
  374. $content_types_xml .= '<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>';
  375. $content_types_xml .= "\n";
  376. $content_types_xml .= '</Types>';
  377. return $content_types_xml;
  378. }
  379. //------------------------------------------------------------------
  380. /*
  381. * @param $row_number int, zero based
  382. * @param $column_number int, zero based
  383. * @return Cell label/coordinates, ex: A1, C3, AA42
  384. * */
  385. public static function xlsCell($row_number, $column_number) {
  386. $n = $column_number;
  387. for ($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
  388. $r = chr($n % 26 + 0x41) . $r;
  389. }
  390. return $r . ($row_number + 1);
  391. }
  392. //------------------------------------------------------------------
  393. public static function log($string) {
  394. file_put_contents("php://stderr", date("Y-m-d H:i:s:") . rtrim(is_array($string) ? json_encode($string) : $string) . "\n");
  395. }
  396. //------------------------------------------------------------------
  397. public static function sanitize_filename($filename) {
  398. //http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx
  399. $nonprinting = array_map('chr', range(0, 31));
  400. $invalid_chars = ['<', '>', '?', '"', ':', '|', '\\', '/', '*', '&'];
  401. $all_invalids = array_merge($nonprinting, $invalid_chars);
  402. return str_replace($all_invalids, "", $filename);
  403. }
  404. //------------------------------------------------------------------
  405. public static function xmlspecialchars($val) {
  406. return str_replace("'", "&#39;", htmlspecialchars($val));
  407. }
  408. //------------------------------------------------------------------
  409. public static function array_first_key(array $arr) {
  410. reset($arr);
  411. $first_key = key($arr);
  412. return $first_key;
  413. }
  414. //------------------------------------------------------------------
  415. public static function convert_date_time($date_input) {
  416. //thanks to Excel::Writer::XLSX::Worksheet.pm (perl)
  417. $days = 0; # Number of days since epoch
  418. $seconds = 0; # Time expressed as fraction of 24h hours in seconds
  419. $year = $month = $day = 0;
  420. $hour = $min = $sec = 0;
  421. $date_time = $date_input;
  422. if (preg_match("/(\d{4})\-(\d{2})\-(\d{2})/", $date_time, $matches))
  423. {
  424. list($junk,$year,$month,$day) = $matches;
  425. }
  426. if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $date_time, $matches))
  427. {
  428. list($junk,$hour,$min,$sec) = $matches;
  429. $seconds = ( $hour * 60 * 60 + $min * 60 + $sec ) / ( 24 * 60 * 60 );
  430. }
  431. //using 1900 as epoch, not 1904, ignoring 1904 special case
  432. # Special cases for Excel.
  433. if ("$year-$month-$day" == '1899-12-31') return $seconds ; # Excel 1900 epoch
  434. if ("$year-$month-$day" == '1900-01-00') return $seconds ; # Excel 1900 epoch
  435. if ("$year-$month-$day" == '1900-02-29') return 60 + $seconds ; # Excel false leapday
  436. # We calculate the date by calculating the number of days since the epoch
  437. # and adjust for the number of leap days. We calculate the number of leap
  438. # days by normalising the year in relation to the epoch. Thus the year 2000
  439. # becomes 100 for 4 and 100 year leapdays and 400 for 400 year leapdays.
  440. $epoch = 1900;
  441. $offset = 0;
  442. $norm = 300;
  443. $range = $year - $epoch;
  444. # Set month days and check for leap year.
  445. $leap = (($year % 400 == 0) || (($year % 4 == 0) && ($year % 100)) ) ? 1 : 0;
  446. $mdays = [ 31, ($leap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
  447. # Some boundary checks
  448. if ($year < $epoch || $year > 9999) return 0;
  449. if ($month < 1 || $month > 12) return 0;
  450. if ($day < 1 || $day > $mdays[$month - 1]) return 0;
  451. # Accumulate the number of days since the epoch.
  452. $days = $day; # Add days for current month
  453. $days += array_sum( array_slice($mdays, 0, $month - 1 ) ); # Add days for past months
  454. $days += $range * 365; # Add days for past years
  455. $days += intval( ( $range ) / 4 ); # Add leapdays
  456. $days -= intval( ( $range + $offset ) / 100 ); # Subtract 100 year leapdays
  457. $days += intval( ( $range + $offset + $norm ) / 400 ); # Add 400 year leapdays
  458. $days -= $leap; # Already counted above
  459. # Adjust for Excel erroneously treating 1900 as a leap year.
  460. if ($days > 59) { $days++;
  461. }
  462. return $days + $seconds;
  463. }
  464. //------------------------------------------------------------------
  465. }
  466. class XLSXWriter_BuffererWriter
  467. {
  468. protected $fd = null;
  469. protected $buffer = '';
  470. protected $check_utf8 = false;
  471. public function __construct($filename, $fd_fopen_flags='w', $check_utf8=false) {
  472. $this->check_utf8 = $check_utf8;
  473. $this->fd = fopen($filename, $fd_fopen_flags);
  474. if ($this->fd === false) {
  475. XLSXWriter::log("Unable to open $filename for writing.");
  476. }
  477. }
  478. public function write($string) {
  479. $this->buffer .= $string;
  480. if (isset($this->buffer[8191])) {
  481. $this->purge();
  482. }
  483. }
  484. protected function purge() {
  485. if ($this->fd) {
  486. if ($this->check_utf8 && !self::isValidUTF8($this->buffer)) {
  487. XLSXWriter::log("Error, invalid UTF8 encoding detected.");
  488. $this->check_utf8 = false;
  489. }
  490. fwrite($this->fd, $this->buffer);
  491. $this->buffer = '';
  492. }
  493. }
  494. public function close() {
  495. $this->purge();
  496. if ($this->fd) {
  497. fclose($this->fd);
  498. $this->fd = null;
  499. }
  500. }
  501. public function __destruct() {
  502. $this->close();
  503. }
  504. public function ftell() {
  505. if ($this->fd) {
  506. $this->purge();
  507. return ftell($this->fd);
  508. }
  509. return -1;
  510. }
  511. public function fseek($pos) {
  512. if ($this->fd) {
  513. $this->purge();
  514. return fseek($this->fd, $pos);
  515. }
  516. return -1;
  517. }
  518. protected static function isValidUTF8($string) {
  519. if (function_exists('mb_check_encoding'))
  520. {
  521. return mb_check_encoding($string, 'UTF-8') ? true : false;
  522. }
  523. return preg_match("//u", $string) ? true : false;
  524. }
  525. }