xlsxwriter.class.php 24 KB

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