xlsxwriter.class.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. <?php
  2. /* @author Mark Jones
  3. * @license MIT License
  4. * */
  5. if (!class_exists('ZipArchive')) { throw new Exception('ZipArchive not found'); }
  6. Class XLSXWriter
  7. {
  8. //------------------------------------------------------------------
  9. protected $author ='Doc Author';
  10. protected $sheets_meta = array();
  11. protected $shared_strings = array();//unique set
  12. protected $shared_string_count = 0;//count of non-unique references to the unique set
  13. protected $temp_files = array();
  14. public function __construct(){}
  15. public function setAuthor($author='') { $this->author=$author; }
  16. public function __destruct()
  17. {
  18. if (!empty($this->temp_files)) {
  19. foreach($this->temp_files as $temp_file) {
  20. @unlink($temp_file);
  21. }
  22. }
  23. }
  24. protected function tempFilename()
  25. {
  26. $filename = tempnam("/tmp", "xlsx_writer_");
  27. $this->temp_files[] = $filename;
  28. return $filename;
  29. }
  30. public function writeToStdOut()
  31. {
  32. $temp_file = $this->tempFilename();
  33. self::writeToFile($temp_file);
  34. readfile($temp_file);
  35. }
  36. public function writeToString()
  37. {
  38. $temp_file = $this->tempFilename();
  39. self::writeToFile($temp_file);
  40. $string = file_get_contents($temp_file);
  41. return $string;
  42. }
  43. public function writeToFile($filename)
  44. {
  45. @unlink($filename);//if the zip already exists, overwrite it
  46. $zip = new ZipArchive();
  47. if (empty($this->sheets_meta)) { self::log("Error in ".__CLASS__."::".__FUNCTION__.", no worksheets defined."); return; }
  48. if (!$zip->open($filename, ZipArchive::CREATE)) { self::log("Error in ".__CLASS__."::".__FUNCTION__.", unable to create zip."); return; }
  49. $zip->addEmptyDir("docProps/");
  50. $zip->addFromString("docProps/app.xml" , self::buildAppXML() );
  51. $zip->addFromString("docProps/core.xml", self::buildCoreXML());
  52. $zip->addEmptyDir("_rels/");
  53. $zip->addFromString("_rels/.rels", self::buildRelationshipsXML());
  54. $zip->addEmptyDir("xl/worksheets/");
  55. foreach($this->sheets_meta as $sheet_meta) {
  56. $zip->addFile($sheet_meta['filename'], "xl/worksheets/".$sheet_meta['xmlname'] );
  57. }
  58. if (!empty($this->shared_strings)) {
  59. $zip->addFile($this->writeSharedStringsXML(), "xl/sharedStrings.xml" ); //$zip->addFromString("xl/sharedStrings.xml", self::buildSharedStringsXML() );
  60. }
  61. $zip->addFromString("xl/workbook.xml" , self::buildWorkbookXML() );
  62. $zip->addFile($this->writeStylesXML(), "xl/styles.xml" ); //$zip->addFromString("xl/styles.xml" , self::buildStylesXML() );
  63. $zip->addFromString("[Content_Types].xml" , self::buildContentTypesXML() );
  64. $zip->addEmptyDir("xl/_rels/");
  65. $zip->addFromString("xl/_rels/workbook.xml.rels", self::buildWorkbookRelsXML() );
  66. $zip->close();
  67. }
  68. public function writeSheet(array $data, $sheet_name='', array $header_types=array() )
  69. {
  70. $data = empty($data) ? array( array('') ) : $data;
  71. $sheet_filename = $this->tempFilename();
  72. $sheet_default = 'Sheet'.(count($this->sheets_meta)+1);
  73. $sheet_name = !empty($sheet_name) ? $sheet_name : $sheet_default;
  74. $this->sheets_meta[] = array('filename'=>$sheet_filename, 'sheetname'=>$sheet_name ,'xmlname'=>strtolower($sheet_default).".xml" );
  75. $header_offset = empty($header_types) ? 0 : 1;
  76. $row_count = count($data) + $header_offset;
  77. $column_count = count($data[self::array_first_key($data)]);
  78. $max_cell = self::xlsCell( $row_count-1, $column_count-1 );
  79. $tabselected = count($this->sheets_meta)==1 ? 'true' : 'false';//only first sheet is selected
  80. $cell_formats_arr = empty($header_types) ? array_fill(0, $column_count, 'string') : array_values($header_types);
  81. $header_row = empty($header_types) ? array() : array_keys($header_types);
  82. $fd = fopen($sheet_filename, "w+");
  83. if ($fd===false) { self::log("write failed in ".__CLASS__."::".__FUNCTION__."."); return; }
  84. fwrite($fd,'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n");
  85. fwrite($fd,'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">');
  86. fwrite($fd, '<sheetPr filterMode="false">');
  87. fwrite($fd, '<pageSetUpPr fitToPage="false"/>');
  88. fwrite($fd, '</sheetPr>');
  89. fwrite($fd, '<dimension ref="A1:'.$max_cell.'"/>');
  90. fwrite($fd, '<sheetViews>');
  91. fwrite($fd, '<sheetView colorId="64" defaultGridColor="true" rightToLeft="false" 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">');
  92. fwrite($fd, '<selection activeCell="A1" activeCellId="0" pane="topLeft" sqref="A1"/>');
  93. fwrite($fd, '</sheetView>');
  94. fwrite($fd, '</sheetViews>');
  95. fwrite($fd, '<cols>');
  96. fwrite($fd, '<col collapsed="false" hidden="false" max="1025" min="1" style="0" width="19"/>');
  97. fwrite($fd, '</cols>');
  98. fwrite($fd, '<sheetData>');
  99. if (!empty($header_row))
  100. {
  101. fwrite($fd, '<row collapsed="false" customFormat="false" customHeight="false" hidden="false" ht="12.1" outlineLevel="0" r="'.(1).'">');
  102. foreach($header_row as $k=>$v)
  103. {
  104. $this->writeCell($fd, 0, $k, $v, $cell_format='string');
  105. }
  106. fwrite($fd, '</row>');
  107. }
  108. foreach($data as $i=>$row)
  109. {
  110. fwrite($fd, '<row collapsed="false" customFormat="false" customHeight="false" hidden="false" ht="12.1" outlineLevel="0" r="'.($i+$header_offset+1).'">');
  111. foreach($row as $k=>$v)
  112. {
  113. $this->writeCell($fd, $i+$header_offset, $k, $v, $cell_formats_arr[$k]);
  114. }
  115. fwrite($fd, '</row>');
  116. }
  117. fwrite($fd, '</sheetData>');
  118. fwrite($fd, '<printOptions headings="false" gridLines="false" gridLinesSet="true" horizontalCentered="false" verticalCentered="false"/>');
  119. fwrite($fd, '<pageMargins left="0.5" right="0.5" top="1.0" bottom="1.0" header="0.5" footer="0.5"/>');
  120. fwrite($fd, '<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"/>');
  121. fwrite($fd, '<headerFooter differentFirst="false" differentOddEven="false">');
  122. fwrite($fd, '<oddHeader>&amp;C&amp;&quot;Times New Roman,Regular&quot;&amp;12&amp;A</oddHeader>');
  123. fwrite($fd, '<oddFooter>&amp;C&amp;&quot;Times New Roman,Regular&quot;&amp;12Page &amp;P</oddFooter>');
  124. fwrite($fd, '</headerFooter>');
  125. fwrite($fd,'</worksheet>');
  126. fclose($fd);
  127. }
  128. protected function writeCell($fd, $row_number, $column_number, $value, $cell_format)
  129. {
  130. static $styles = array('money'=>1,'dollar'=>1,'datetime'=>2,'date'=>3,'string'=>0);
  131. $cell = self::xlsCell($row_number, $column_number);
  132. $s = isset($styles[$cell_format]) ? $styles[$cell_format] : '0';
  133. if (is_numeric($value)) {
  134. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'" t="n"><v>'.($value*1).'</v></c>');//int,float, etc
  135. } else if ($cell_format=='date') {
  136. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'" t="n"><v>'.intval(self::convert_date_time($value)).'</v></c>');
  137. } else if ($cell_format=='datetime') {
  138. if ($value === '') {
  139. fwrite($fd,'<c r="'.$cell.'" s="0"/>');
  140. } else {
  141. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'" t="n"><v>'.self::convert_date_time($value).'</v></c>');
  142. }
  143. } else if ($value==''){
  144. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'"/>');
  145. } else if ($value{0}=='='){
  146. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'" t="s"><f>'.self::xmlspecialchars($value).'</f></c>');
  147. } else if ($value!==''){
  148. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'" t="s"><v>'.self::xmlspecialchars($this->setSharedString($value)).'</v></c>');
  149. }
  150. }
  151. protected function writeStylesXML()
  152. {
  153. $tempfile = $this->tempFilename();
  154. $fd = fopen($tempfile, "w+");
  155. if ($fd===false) { self::log("write failed in ".__CLASS__."::".__FUNCTION__."."); return; }
  156. fwrite($fd, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n");
  157. fwrite($fd, '<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">');
  158. fwrite($fd, '<numFmts count="4">');
  159. fwrite($fd, '<numFmt formatCode="GENERAL" numFmtId="164"/>');
  160. fwrite($fd, '<numFmt formatCode="[$$-1009]#,##0.00;[RED]\-[$$-1009]#,##0.00" numFmtId="165"/>');
  161. fwrite($fd, '<numFmt formatCode="YYYY-MM-DD\ HH:MM:SS" numFmtId="166"/>');
  162. fwrite($fd, '<numFmt formatCode="YYYY-MM-DD" numFmtId="167"/>');
  163. fwrite($fd, '</numFmts>');
  164. fwrite($fd, '<fonts count="4">');
  165. fwrite($fd, '<font><name val="Arial"/><charset val="1"/><family val="2"/><sz val="10"/></font>');
  166. fwrite($fd, '<font><name val="Arial"/><family val="0"/><sz val="10"/></font>');
  167. fwrite($fd, '<font><name val="Arial"/><family val="0"/><sz val="10"/></font>');
  168. fwrite($fd, '<font><name val="Arial"/><family val="0"/><sz val="10"/></font>');
  169. fwrite($fd, '</fonts>');
  170. fwrite($fd, '<fills count="2"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill></fills>');
  171. fwrite($fd, '<borders count="1"><border diagonalDown="false" diagonalUp="false"><left/><right/><top/><bottom/><diagonal/></border></borders>');
  172. fwrite($fd, '<cellStyleXfs count="15">');
  173. fwrite($fd, '<xf applyAlignment="true" applyBorder="true" applyFont="true" applyProtection="true" borderId="0" fillId="0" fontId="0" numFmtId="164">');
  174. fwrite($fd, '<alignment horizontal="general" indent="0" shrinkToFit="false" textRotation="0" vertical="bottom" wrapText="false"/>');
  175. fwrite($fd, '<protection hidden="false" locked="true"/>');
  176. fwrite($fd, '</xf>');
  177. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="0"/>');
  178. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="0"/>');
  179. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="2" numFmtId="0"/>');
  180. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="2" numFmtId="0"/>');
  181. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  182. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  183. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  184. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  185. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  186. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  187. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  188. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  189. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  190. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  191. //fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="43"/>');
  192. //fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="41"/>');
  193. //fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="44"/>');
  194. //fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="42"/>');
  195. //fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="9"/>');
  196. fwrite($fd, '</cellStyleXfs>');
  197. fwrite($fd, '<cellXfs count="4">');
  198. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="164" xfId="0"/>');
  199. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="165" xfId="0"/>');
  200. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="166" xfId="0"/>');
  201. fwrite($fd, '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="167" xfId="0"/>');
  202. fwrite($fd, '</cellXfs>');
  203. fwrite($fd, '<cellStyles count="1">');
  204. fwrite($fd, '<cellStyle builtinId="0" customBuiltin="false" name="Normal" xfId="0"/>');
  205. //fwrite($fd, '<cellStyle builtinId="3" customBuiltin="false" name="Comma" xfId="15"/>');
  206. //fwrite($fd, '<cellStyle builtinId="6" customBuiltin="false" name="Comma [0]" xfId="16"/>');
  207. //fwrite($fd, '<cellStyle builtinId="4" customBuiltin="false" name="Currency" xfId="17"/>');
  208. //fwrite($fd, '<cellStyle builtinId="7" customBuiltin="false" name="Currency [0]" xfId="18"/>');
  209. //fwrite($fd, '<cellStyle builtinId="5" customBuiltin="false" name="Percent" xfId="19"/>');
  210. fwrite($fd, '</cellStyles>');
  211. fwrite($fd, '</styleSheet>');
  212. fclose($fd);
  213. return $tempfile;
  214. }
  215. protected function setSharedString($v)
  216. {
  217. // Strip control characters which Excel does not seem to like...
  218. $v = preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F]/u', '', $v);
  219. if (isset($this->shared_strings[$v]))
  220. {
  221. $string_value = $this->shared_strings[$v];
  222. }
  223. else
  224. {
  225. $string_value = count($this->shared_strings);
  226. $this->shared_strings[$v] = $string_value;
  227. }
  228. $this->shared_string_count++;//non-unique count
  229. return $string_value;
  230. }
  231. protected function writeSharedStringsXML()
  232. {
  233. $tempfile = $this->tempFilename();
  234. $fd = fopen($tempfile, "w+");
  235. if ($fd===false) { self::log("write failed in ".__CLASS__."::".__FUNCTION__."."); return; }
  236. fwrite($fd,'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n");
  237. fwrite($fd,'<sst count="'.($this->shared_string_count).'" uniqueCount="'.count($this->shared_strings).'" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">');
  238. foreach($this->shared_strings as $s=>$c)
  239. {
  240. fwrite($fd,'<si><t>'.self::xmlspecialchars($s).'</t></si>');
  241. }
  242. fwrite($fd, '</sst>');
  243. fclose($fd);
  244. return $tempfile;
  245. }
  246. protected function buildAppXML()
  247. {
  248. $app_xml="";
  249. $app_xml.='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n";
  250. $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>';
  251. return $app_xml;
  252. }
  253. protected function buildCoreXML()
  254. {
  255. $core_xml="";
  256. $core_xml.='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n";
  257. $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">';
  258. $core_xml.='<dcterms:created xsi:type="dcterms:W3CDTF">'.date("Y-m-d\TH:i:s.00\Z").'</dcterms:created>';//$date_time = '2013-07-25T15:54:37.00Z';
  259. $core_xml.='<dc:creator>'.self::xmlspecialchars($this->author).'</dc:creator>';
  260. $core_xml.='<cp:revision>0</cp:revision>';
  261. $core_xml.='</cp:coreProperties>';
  262. return $core_xml;
  263. }
  264. protected function buildRelationshipsXML()
  265. {
  266. $rels_xml="";
  267. $rels_xml.='<?xml version="1.0" encoding="UTF-8"?>'."\n";
  268. $rels_xml.='<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">';
  269. $rels_xml.='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>';
  270. $rels_xml.='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>';
  271. $rels_xml.='<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>';
  272. $rels_xml.="\n";
  273. $rels_xml.='</Relationships>';
  274. return $rels_xml;
  275. }
  276. protected function buildWorkbookXML()
  277. {
  278. $workbook_xml="";
  279. $workbook_xml.='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n";
  280. $workbook_xml.='<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">';
  281. $workbook_xml.='<fileVersion appName="Calc"/><workbookPr backupFile="false" showObjects="all" date1904="false"/><workbookProtection/>';
  282. $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>';
  283. $workbook_xml.='<sheets>';
  284. foreach($this->sheets_meta as $i=>$sheet_meta) {
  285. $workbook_xml.='<sheet name="'.self::xmlspecialchars($sheet_meta['sheetname']).'" sheetId="'.($i+1).'" state="visible" r:id="rId'.($i+2).'"/>';
  286. }
  287. $workbook_xml.='</sheets>';
  288. $workbook_xml.='<calcPr iterateCount="100" refMode="A1" iterate="false" iterateDelta="0.001"/></workbook>';
  289. return $workbook_xml;
  290. }
  291. protected function buildWorkbookRelsXML()
  292. {
  293. $wkbkrels_xml="";
  294. $wkbkrels_xml.='<?xml version="1.0" encoding="UTF-8"?>'."\n";
  295. $wkbkrels_xml.='<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">';
  296. $wkbkrels_xml.='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>';
  297. foreach($this->sheets_meta as $i=>$sheet_meta) {
  298. $wkbkrels_xml.='<Relationship Id="rId'.($i+2).'" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/'.($sheet_meta['xmlname']).'"/>';
  299. }
  300. if (!empty($this->shared_strings)) {
  301. $wkbkrels_xml.='<Relationship Id="rId'.(count($this->sheets_meta)+2).'" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>';
  302. }
  303. $wkbkrels_xml.="\n";
  304. $wkbkrels_xml.='</Relationships>';
  305. return $wkbkrels_xml;
  306. }
  307. protected function buildContentTypesXML()
  308. {
  309. $content_types_xml="";
  310. $content_types_xml.='<?xml version="1.0" encoding="UTF-8"?>'."\n";
  311. $content_types_xml.='<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">';
  312. $content_types_xml.='<Override PartName="/_rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
  313. $content_types_xml.='<Override PartName="/xl/_rels/workbook.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
  314. foreach($this->sheets_meta as $i=>$sheet_meta) {
  315. $content_types_xml.='<Override PartName="/xl/worksheets/'.($sheet_meta['xmlname']).'" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
  316. }
  317. if (!empty($this->shared_strings)) {
  318. $content_types_xml.='<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>';
  319. }
  320. $content_types_xml.='<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>';
  321. $content_types_xml.='<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>';
  322. $content_types_xml.='<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>';
  323. $content_types_xml.='<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>';
  324. $content_types_xml.="\n";
  325. $content_types_xml.='</Types>';
  326. return $content_types_xml;
  327. }
  328. //------------------------------------------------------------------
  329. /*
  330. * @param $row_number int, zero based
  331. * @param $column_number int, zero based
  332. * @return Cell label/coordinates, ex: A1, C3, AA42
  333. * */
  334. public static function xlsCell($row_number, $column_number)
  335. {
  336. $n = $column_number;
  337. for($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
  338. $r = chr($n%26 + 0x41) . $r;
  339. }
  340. return $r . ($row_number+1);
  341. }
  342. //------------------------------------------------------------------
  343. public static function log($string)
  344. {
  345. file_put_contents("php://stderr", date("Y-m-d H:i:s:").rtrim(is_array($string) ? json_encode($string) : $string)."\n");
  346. }
  347. //------------------------------------------------------------------
  348. public static function xmlspecialchars($val)
  349. {
  350. return str_replace("'", "&#39;", htmlspecialchars($val));
  351. }
  352. //------------------------------------------------------------------
  353. public static function array_first_key(array $arr)
  354. {
  355. reset($arr);
  356. $first_key = key($arr);
  357. return $first_key;
  358. }
  359. //------------------------------------------------------------------
  360. public static function convert_date_time($date_input) //thanks to Excel::Writer::XLSX::Worksheet.pm (perl)
  361. {
  362. $days = 0; # Number of days since epoch
  363. $seconds = 0; # Time expressed as fraction of 24h hours in seconds
  364. $year=$month=$day=0;
  365. $hour=$min =$sec=0;
  366. $date_time = $date_input;
  367. if (preg_match("/(\d{4})\-(\d{2})\-(\d{2})/", $date_time, $matches))
  368. {
  369. list($junk,$year,$month,$day) = $matches;
  370. }
  371. if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $date_time, $matches))
  372. {
  373. list($junk,$hour,$min,$sec) = $matches;
  374. $seconds = ( $hour * 60 * 60 + $min * 60 + $sec ) / ( 24 * 60 * 60 );
  375. }
  376. //using 1900 as epoch, not 1904, ignoring 1904 special case
  377. # Special cases for Excel.
  378. if ("$year-$month-$day"=='1899-12-31') return $seconds ; # Excel 1900 epoch
  379. if ("$year-$month-$day"=='1900-01-00') return $seconds ; # Excel 1900 epoch
  380. if ("$year-$month-$day"=='1900-02-29') return 60 + $seconds ; # Excel false leapday
  381. # We calculate the date by calculating the number of days since the epoch
  382. # and adjust for the number of leap days. We calculate the number of leap
  383. # days by normalising the year in relation to the epoch. Thus the year 2000
  384. # becomes 100 for 4 and 100 year leapdays and 400 for 400 year leapdays.
  385. $epoch = 1900;
  386. $offset = 0;
  387. $norm = 300;
  388. $range = $year - $epoch;
  389. # Set month days and check for leap year.
  390. $leap = (($year % 400 == 0) || (($year % 4 == 0) && ($year % 100)) ) ? 1 : 0;
  391. $mdays = array( 31, ($leap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
  392. # Some boundary checks
  393. if($year < $epoch || $year > 9999) return 0;
  394. if($month < 1 || $month > 12) return 0;
  395. if($day < 1 || $day > $mdays[ $month - 1 ]) return 0;
  396. # Accumulate the number of days since the epoch.
  397. $days = $day; # Add days for current month
  398. $days += array_sum( array_slice($mdays, 0, $month-1 ) ); # Add days for past months
  399. $days += $range * 365; # Add days for past years
  400. $days += intval( ( $range ) / 4 ); # Add leapdays
  401. $days -= intval( ( $range + $offset ) / 100 ); # Subtract 100 year leapdays
  402. $days += intval( ( $range + $offset + $norm ) / 400 ); # Add 400 year leapdays
  403. $days -= $leap; # Already counted above
  404. # Adjust for Excel erroneously treating 1900 as a leap year.
  405. if ($days > 59) { $days++;}
  406. return $days + $seconds;
  407. }
  408. //------------------------------------------------------------------
  409. }