/xlsxwriter.class.php

https://github.com/SystemDevil/PHP_XLSXWriter_plus · PHP · 633 lines · 579 code · 42 blank · 12 comment · 103 complexity · e787a79c618abff5e315874af4961682 MD5 · raw file

  1. <?php
  2. /*
  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 $defaultFontName = 'Calibri';
  11. protected $defaultFontSize = 11;
  12. protected $defaultWrapText = false;
  13. protected $defaultVerticalAlign = 'top';
  14. protected $defaultHorizontalAlign = 'left';
  15. protected $defaultStartRow = 0;
  16. protected $defaultStartCol = 0;
  17. protected $defaultStyle = array();
  18. protected $fontsCount = 1; //1 font must be in structure
  19. protected $fontSize = 8;
  20. protected $fontColor = '';
  21. protected $fontStyles = '';
  22. protected $fontName = '';
  23. protected $fontId = 0; //font counting from index - 0, means 0,1 - 2 elements
  24. protected $bordersCount = 1; //1 border must be in structure
  25. protected $bordersStyle = '';
  26. protected $bordersColor = '';
  27. protected $borderId = 0; //borders counting from index - 0, means 0,1 - 2 elements
  28. protected $fillsCount = 2; //2 fills must be in structure
  29. protected $fillColor = '';
  30. protected $fillId = 1; //fill counting from index - 0, means 0,1 - 2 elements
  31. protected $stylesCount = 1;//1 style must be in structure
  32. protected $sheets_meta = array();
  33. protected $shared_strings = array();//unique set
  34. protected $shared_string_count = 0;//count of non-unique references to the unique set
  35. protected $temp_files = array();
  36. public function __construct(){}
  37. public function setAuthor($author='') { $this->author=$author; }
  38. public function setFontName($defaultFontName) { $this->defaultFontName=$defaultFontName; }
  39. public function setFontSize($defaultFontSize) { $this->defaultFontSize=$defaultFontSize; }
  40. public function setWrapText($defaultWrapText) { $this->defaultWrapText=$defaultWrapText; }
  41. public function setVerticalAlign($defaultVerticalAlign) { $this->defaultVerticalAlign=$defaultVerticalAlign; }
  42. public function setHorizontalAlign($defaultHorizontalAlign) { $this->defaultHorizontalAlign=$defaultHorizontalAlign; }
  43. private function setStyle($defaultStyle) { $this->defaultStyle=$defaultStyle; }
  44. public function setStartRow($defaultStartRow) { $this->defaultStartRow=($defaultStartRow > 0) ? ((int)$defaultStartRow - 1) : 0; }
  45. public function setStartCol($defaultStartCol) { $this->defaultStartCol=($defaultStartCol > 0) ? ((int)$defaultStartCol - 1) : 0; }
  46. public function __destruct()
  47. {
  48. if (!empty($this->temp_files)) {
  49. foreach($this->temp_files as $temp_file) {
  50. @unlink($temp_file);
  51. }
  52. }
  53. }
  54. protected function tempFilename()
  55. {
  56. $filename = tempnam("/tmp", "xlsx_writer_");
  57. $this->temp_files[] = $filename;
  58. return $filename;
  59. }
  60. public function writeToStdOut()
  61. {
  62. $temp_file = $this->tempFilename();
  63. self::writeToFile($temp_file);
  64. readfile($temp_file);
  65. }
  66. public function writeToString()
  67. {
  68. $temp_file = $this->tempFilename();
  69. self::writeToFile($temp_file);
  70. $string = file_get_contents($temp_file);
  71. return $string;
  72. }
  73. public function writeToFile($filename)
  74. {
  75. @unlink($filename);//if the zip already exists, overwrite it
  76. $zip = new ZipArchive();
  77. if (empty($this->sheets_meta)) { self::log("Error in ".__CLASS__."::".__FUNCTION__.", no worksheets defined."); return; }
  78. if (!$zip->open($filename, ZipArchive::CREATE)) { self::log("Error in ".__CLASS__."::".__FUNCTION__.", unable to create zip."); return; }
  79. $zip->addEmptyDir("docProps/");
  80. $zip->addFromString("docProps/app.xml" , self::buildAppXML() );
  81. $zip->addFromString("docProps/core.xml", self::buildCoreXML());
  82. $zip->addEmptyDir("_rels/");
  83. $zip->addFromString("_rels/.rels", self::buildRelationshipsXML());
  84. $zip->addEmptyDir("xl/worksheets/");
  85. foreach($this->sheets_meta as $sheet_meta) {
  86. $zip->addFile($sheet_meta['filename'], "xl/worksheets/".$sheet_meta['xmlname'] );
  87. }
  88. if (!empty($this->shared_strings)) {
  89. $zip->addFile($this->writeSharedStringsXML(), "xl/sharedStrings.xml" ); //$zip->addFromString("xl/sharedStrings.xml", self::buildSharedStringsXML() );
  90. }
  91. $zip->addFromString("xl/workbook.xml" , self::buildWorkbookXML() );
  92. $zip->addFile($this->writeStylesXML(), "xl/styles.xml" ); //$zip->addFromString("xl/styles.xml" , self::buildStylesXML() );
  93. $zip->addFromString("[Content_Types].xml" , self::buildContentTypesXML() );
  94. $zip->addEmptyDir("xl/_rels/");
  95. $zip->addFromString("xl/_rels/workbook.xml.rels", self::buildWorkbookRelsXML() );
  96. $zip->close();
  97. }
  98. public function writeSheet(array $data, $sheet_name='', array $header_types=array(), array $styles )
  99. {
  100. for ($i = 0; $i < count($styles); $i++) {
  101. $styles[$i] += array('sheet' => $sheet_name);
  102. }
  103. $this->setStyle(array_merge((array)$this->defaultStyle, (array)$styles));
  104. $data = empty($data) ? array( array('') ) : $data;
  105. $sheet_filename = $this->tempFilename();
  106. $sheet_default = 'Sheet'.(count($this->sheets_meta)+1);
  107. $sheet_name = !empty($sheet_name) ? $sheet_name : $sheet_default;
  108. $this->sheets_meta[] = array('filename'=>$sheet_filename, 'sheetname'=>$sheet_name ,'xmlname'=>strtolower($sheet_default).".xml" );
  109. $header_offset = empty($header_types) ? 0 : $this->defaultStartRow + 1;
  110. $row_count = count($data) + $header_offset;
  111. $column_count = count($data[self::array_first_key($data)]);
  112. $max_cell = self::xlsCell( $row_count-1, $column_count-1 );
  113. $tabselected = count($this->sheets_meta)==1 ? 'true' : 'false';//only first sheet is selected
  114. $cell_formats_arr = empty($header_types) ? array_fill(0, $column_count, 'string') : array_values($header_types);
  115. $header_row = empty($header_types) ? array() : array_keys($header_types);
  116. $fd = fopen($sheet_filename, "w+");
  117. if ($fd===false) { self::log("write failed in ".__CLASS__."::".__FUNCTION__."."); return; }
  118. fwrite($fd,'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n");
  119. fwrite($fd,'<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">');
  120. fwrite($fd, '<sheetPr filterMode="false">');
  121. fwrite($fd, '<pageSetUpPr fitToPage="false"/>');
  122. fwrite($fd, '</sheetPr>');
  123. fwrite($fd, '<dimension ref="A1:'.$max_cell.'"/>');
  124. fwrite($fd, '<sheetViews>');
  125. 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">');
  126. fwrite($fd, '<selection activeCell="A1" activeCellId="0" pane="topLeft" sqref="A1"/>');
  127. fwrite($fd, '</sheetView>');
  128. fwrite($fd, '</sheetViews>');
  129. fwrite($fd, '<cols>');
  130. fwrite($fd, '<col collapsed="false" hidden="false" max="1025" min="1" style="0" width="11.5"/>');
  131. fwrite($fd, '</cols>');
  132. fwrite($fd, '<sheetData>');
  133. if (!empty($header_row))
  134. {
  135. fwrite($fd, '<row collapsed="false" customFormat="false" customHeight="false" hidden="false" ht="12.1" outlineLevel="0" r="'.($this->defaultStartRow + 1).'">');
  136. foreach($header_row as $k=>$v)
  137. {
  138. $this->writeCell($fd, $this->defaultStartRow + 0, $this->defaultStartCol + $k, $v, $sheet_name);
  139. }
  140. fwrite($fd, '</row>');
  141. }
  142. foreach($data as $i=>$row)
  143. {
  144. fwrite($fd, '<row collapsed="false" customFormat="false" customHeight="false" hidden="false" ht="12.1" outlineLevel="0" r="'.($i+$header_offset+1).'">');
  145. foreach($row as $k=>$v)
  146. {
  147. $this->writeCell($fd, $i+$header_offset, $this->defaultStartCol + $k, $v, $sheet_name);
  148. }
  149. fwrite($fd, '</row>');
  150. }
  151. fwrite($fd, '</sheetData>');
  152. fwrite($fd, '<printOptions headings="false" gridLines="false" gridLinesSet="true" horizontalCentered="false" verticalCentered="false"/>');
  153. fwrite($fd, '<pageMargins left="0.5" right="0.5" top="1.0" bottom="1.0" header="0.5" footer="0.5"/>');
  154. 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"/>');
  155. fwrite($fd, '<headerFooter differentFirst="false" differentOddEven="false">');
  156. fwrite($fd, '<oddHeader>&amp;C&amp;&quot;Times New Roman,Regular&quot;&amp;12&amp;A</oddHeader>');
  157. fwrite($fd, '<oddFooter>&amp;C&amp;&quot;Times New Roman,Regular&quot;&amp;12Page &amp;P</oddFooter>');
  158. fwrite($fd, '</headerFooter>');
  159. fwrite($fd,'</worksheet>');
  160. fclose($fd);
  161. }
  162. protected function writeCell($fd, $row_number, $column_number, $value, $sheet_name)
  163. {
  164. $cell = self::xlsCell($row_number, $column_number);
  165. $s = '0';
  166. if ($this->defaultStyle) {
  167. foreach ($this->defaultStyle as $key => $style) {
  168. if (isset($style['sheet'])) {
  169. if ($style['sheet'] == $sheet_name) {
  170. if (isset($style['allfilleddata'])) {
  171. $s = $key + 1;
  172. } else {
  173. if (isset($style['columns'])) {
  174. if (is_array($style['columns'])) {
  175. if (in_array($column_number, $style['columns'])) $s = $key + 1;
  176. } else {
  177. if ($column_number == $style['columns']) $s = $key + 1;
  178. }
  179. } elseif (isset($style['rows'])) {
  180. if (is_array($style['rows'])) {
  181. if (in_array($row_number, $style['rows'])) $s = $key + 1;
  182. } else {
  183. if ($row_number == $style['rows']) $s = $key + 1;
  184. }
  185. } elseif (isset($style['cells'])) {
  186. if (is_array($style['cells'])) {
  187. if (in_array($cell, $style['cells'])) $s = $key + 1;
  188. } else {
  189. if ($cell == $style['cells']) $s = $key + 1;
  190. }
  191. }
  192. }
  193. }
  194. }
  195. }
  196. }
  197. if (is_numeric($value)) {
  198. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'" t="n"><v>'.($value*1).'</v></c>');//int,float, etc
  199. } else if ($cell_format=='date') {
  200. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'" t="n"><v>'.intval(self::convert_date_time($value)).'</v></c>');
  201. } else if ($cell_format=='datetime') {
  202. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'" t="n"><v>'.self::convert_date_time($value).'</v></c>');
  203. } else if ($value==''){
  204. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'"/>');
  205. } else if ($value{0}=='='){
  206. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'" t="s"><f>'.self::xmlspecialchars($value).'</f></c>');
  207. } else if ($value!==''){
  208. fwrite($fd,'<c r="'.$cell.'" s="'.$s.'" t="s"><v>'.self::xmlspecialchars($this->setSharedString($value)).'</v></c>');
  209. }
  210. }
  211. protected function writeStylesXML()
  212. {
  213. $tempfile = $this->tempFilename();
  214. $fd = fopen($tempfile, "w+");
  215. if ($fd===false) { self::log("write failed in ".__CLASS__."::".__FUNCTION__."."); return; }
  216. fwrite($fd, '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n");
  217. fwrite($fd, '<styleSheet xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" mc:Ignorable="x14ac" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">');
  218. if ($this->defaultStyle) {
  219. foreach ($this->defaultStyle as $style) {
  220. if (isset($style['sheet'])) {
  221. if (isset($style['font'])) $this->fontsCount++;
  222. }
  223. }
  224. }
  225. fwrite($fd, '<fonts x14ac:knownFonts="1" count="'.$this->fontsCount.'">');
  226. fwrite($fd, ' <font>');
  227. fwrite($fd, ' <sz val="'.$this->defaultFontSize.'"/>');
  228. fwrite($fd, ' <color theme="1"/>');
  229. fwrite($fd, ' <name val="'.$this->defaultFontName.'"/>');
  230. fwrite($fd, ' <family val="2"/>');
  231. if ($this->defaultFontName == 'MS Sans Serif') {
  232. fwrite($fd, ' <charset val="204"/>');
  233. } else if ($this->defaultFontName == 'Calibri') {
  234. fwrite($fd, ' <scheme val="minor"/>');
  235. } else {
  236. fwrite($fd, ' <charset val="204"/>');
  237. }
  238. fwrite($fd, ' </font>');
  239. if ($this->defaultStyle) {
  240. foreach ($this->defaultStyle as $style) {
  241. if (isset($style['sheet'])) {
  242. if (isset($style['font'])) {
  243. if (isset($style['font']['name'])) $this->fontName = $style['font']['name'];
  244. if (isset($style['font']['size'])) $this->fontSize = $style['font']['size'];
  245. if (isset($style['font']['color'])) $this->fontColor = $style['font']['color'];
  246. if ($style['font']['bold']) $this->fontStyles .= '<b/>';
  247. if ($style['font']['italic']) $this->fontStyles .= '<i/>';
  248. if ($style['font']['underline']) $this->fontStyles .= '<u/>';
  249. fwrite($fd, ' <font>');
  250. if ($this->fontStyles) fwrite($fd, ' '.$this->fontStyles);
  251. fwrite($fd, ' <sz val="'.$this->fontSize.'"/>');
  252. if ($this->fontColor) {
  253. fwrite($fd, ' <color rgb="FF'.$this->fontColor.'"/>');
  254. } else {
  255. fwrite($fd, ' <color theme="1"/>');
  256. }
  257. fwrite($fd, ' <name val="'.$this->fontName.'"/>');
  258. fwrite($fd, ' <fasmily val="2"/>');
  259. if ($this->fontName == 'MS Sans Serif') {
  260. fwrite($fd, ' <charset val="204"/>');
  261. } else if ($this->fontName == 'Calibri') {
  262. fwrite($fd, ' <scheme val="minor"/>');
  263. } else {
  264. fwrite($fd, ' <charset val="204"/>');
  265. }
  266. fwrite($fd, ' </font>');
  267. }
  268. $this->fontStyles = '';
  269. }
  270. }
  271. }
  272. fwrite($fd, '</fonts>');
  273. if ($this->defaultStyle) {
  274. foreach ($this->defaultStyle as $style) {
  275. if (isset($style['sheet'])) {
  276. if (isset($style['fill'])) $this->fillsCount++;
  277. }
  278. }
  279. }
  280. fwrite($fd, '<fills count="'.$this->fillsCount.'">');
  281. fwrite($fd, ' <fill><patternFill patternType="none"/></fill>');
  282. fwrite($fd, ' <fill><patternFill patternType="gray125"/></fill>');
  283. if ($this->defaultStyle) {
  284. foreach ($this->defaultStyle as $style) {
  285. if (isset($style['sheet'])) {
  286. if (isset($style['fill'])) {
  287. if (isset($style['fill']['color'])) $this->fillColor = $style['fill']['color'];
  288. fwrite($fd, ' <fill>');
  289. fwrite($fd, ' <patternFill patternType="solid">');
  290. fwrite($fd, ' <fgColor rgb="FF'.$this->fillColor.'"/>');
  291. fwrite($fd, ' <bgColor indexed="64"/>');
  292. fwrite($fd, ' </patternFill>');
  293. fwrite($fd, ' </fill>');
  294. }
  295. }
  296. }
  297. }
  298. fwrite($fd, '</fills>');
  299. if ($this->defaultStyle) {
  300. foreach ($this->defaultStyle as $style) {
  301. if (isset($style['sheet'])) {
  302. if (isset($style['border'])) $this->bordersCount++;
  303. }
  304. }
  305. }
  306. fwrite($fd, '<borders count="'.$this->bordersCount.'">');
  307. fwrite($fd, ' <border>');
  308. fwrite($fd, ' <left/><right/><top/><bottom/><diagonal/>');
  309. fwrite($fd, ' </border>');
  310. if ($this->defaultStyle) {
  311. foreach ($this->defaultStyle as $style) {
  312. if (isset($style['sheet'])) {
  313. if (isset($style['border'])) {
  314. if (isset($style['border']['style'])) $this->bordersStyle = ' style="'.$style['border']['style'].'"';
  315. if (isset($style['border']['color'])) $this->bordersColor = '<color rgb="FF'.$style['border']['color'].'"/>';
  316. fwrite($fd, ' <border>');
  317. fwrite($fd, ' <left'.$this->bordersStyle.'>'.$this->bordersColor.'</left>');
  318. fwrite($fd, ' <right'.$this->bordersStyle.'>'.$this->bordersColor.'</right>');
  319. fwrite($fd, ' <top'.$this->bordersStyle.'>'.$this->bordersColor.'</top>');
  320. fwrite($fd, ' <bottom'.$this->bordersStyle.'>'.$this->bordersColor.'</bottom>');
  321. fwrite($fd, ' <diagonal/>');
  322. fwrite($fd, ' </border>');
  323. }
  324. }
  325. }
  326. }
  327. fwrite($fd, '</borders>');
  328. fwrite($fd, '<cellStyleXfs count="1">');
  329. fwrite($fd, '<xf borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  330. fwrite($fd, '</cellStyleXfs>');
  331. $this->stylesCount += count($this->defaultStyle);
  332. fwrite($fd, '<cellXfs count="'.$this->stylesCount.'">');
  333. $this->defaultWrapText = ($this->defaultWrapText) ? '1' : '0';
  334. fwrite($fd, '<xf borderId="0" fillId="0" fontId="0" numFmtId="0" xfId="0"><alignment wrapText="'.$this->defaultWrapText.'" vertical="'.$this->defaultVerticalAlign.'" horizontal="'.$this->defaultHorizontalAlign.'"/></xf>');
  335. if ($this->defaultStyle) {
  336. foreach ($this->defaultStyle as $style) {
  337. if (isset($style['sheet'])) {
  338. if (isset($style['font'])) {
  339. $font_Id = $this->fontId += 1;
  340. } else {
  341. $font_Id = 0;
  342. }
  343. if (isset($style['fill'])) {
  344. $fill_Id = $this->fillId += 1;
  345. } else {
  346. $fill_Id = 0;
  347. }
  348. if (isset($style['border'])) {
  349. $border_Id = $this->borderId += 1;
  350. } else {
  351. $border_Id = 0;
  352. }
  353. if (isset($style['wrapText'])) {
  354. $wrapText = ($style['wrapText']) ? '1' : '0';
  355. } else {
  356. $wrapText = $this->defaultWrapText;
  357. }
  358. $format_Id = (isset($style['format'])) ? $style['format'] : '0';
  359. if (isset($style['verticalAlign'])) {
  360. $verticalAlign = $style['verticalAlign'];
  361. } else {
  362. $verticalAlign = $this->defaultVerticalAlign;
  363. }
  364. if (isset($style['horizontalAlign'])) {
  365. $horizontalAlign = $style['horizontalAlign'];
  366. } else {
  367. $horizontalAlign = $this->defaultHorizontalAlign;
  368. }
  369. fwrite($fd, '<xf borderId="'.$border_Id.'" fillId="'.$fill_Id.'" fontId="'.$font_Id.'" numFmtId="'.$format_Id.'" xfId="0" applyFill="1">');
  370. fwrite($fd, '<alignment wrapText="'.$wrapText.'" vertical="'.$verticalAlign.'" horizontal="'.$horizontalAlign.'"/>');
  371. fwrite($fd, '</xf>');
  372. }
  373. }
  374. }
  375. fwrite($fd, '</cellXfs>');
  376. fwrite($fd, '<cellStyles count="1">');
  377. fwrite($fd, '<cellStyle xfId="0" builtinId="0" name="Normal"/>');
  378. fwrite($fd, '</cellStyles>');
  379. fwrite($fd, '<dxfs count="0"/>');
  380. fwrite($fd, '<tableStyles count="0" defaultPivotStyle="PivotStyleMedium9" defaultTableStyle="TableStyleMedium2"/>');
  381. fwrite($fd, '<extLst>');
  382. fwrite($fd, '<ext xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" uri="{EB79DEF2-80B8-43e5-95BD-54CBDDF9020C}">');
  383. fwrite($fd, '<x14:slicerStyles defaultSlicerStyle="SlicerStyleLight1"/>');
  384. fwrite($fd, '</ext>');
  385. fwrite($fd, '</extLst>');
  386. fwrite($fd, '</styleSheet>');
  387. fclose($fd);
  388. return $tempfile;
  389. }
  390. protected function setSharedString($v)
  391. {
  392. if (isset($this->shared_strings[$v]))
  393. {
  394. $string_value = $this->shared_strings[$v];
  395. }
  396. else
  397. {
  398. $string_value = count($this->shared_strings);
  399. $this->shared_strings[$v] = $string_value;
  400. }
  401. $this->shared_string_count++;//non-unique count
  402. return $string_value;
  403. }
  404. protected function writeSharedStringsXML()
  405. {
  406. $tempfile = $this->tempFilename();
  407. $fd = fopen($tempfile, "w+");
  408. if ($fd===false) { self::log("write failed in ".__CLASS__."::".__FUNCTION__."."); return; }
  409. fwrite($fd,'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n");
  410. fwrite($fd,'<sst count="'.($this->shared_string_count).'" uniqueCount="'.count($this->shared_strings).'" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">');
  411. foreach($this->shared_strings as $s=>$c)
  412. {
  413. fwrite($fd,'<si><t>'.self::xmlspecialchars($s).'</t></si>');
  414. }
  415. fwrite($fd, '</sst>');
  416. fclose($fd);
  417. return $tempfile;
  418. }
  419. protected function buildAppXML()
  420. {
  421. $app_xml="";
  422. $app_xml.='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n";
  423. $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>';
  424. return $app_xml;
  425. }
  426. protected function buildCoreXML()
  427. {
  428. $core_xml="";
  429. $core_xml.='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n";
  430. $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">';
  431. $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';
  432. $core_xml.='<dc:creator>'.self::xmlspecialchars($this->author).'</dc:creator>';
  433. $core_xml.='<cp:revision>0</cp:revision>';
  434. $core_xml.='</cp:coreProperties>';
  435. return $core_xml;
  436. }
  437. protected function buildRelationshipsXML()
  438. {
  439. $rels_xml="";
  440. $rels_xml.='<?xml version="1.0" encoding="UTF-8"?>'."\n";
  441. $rels_xml.='<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">';
  442. $rels_xml.='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>';
  443. $rels_xml.='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>';
  444. $rels_xml.='<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>';
  445. $rels_xml.="\n";
  446. $rels_xml.='</Relationships>';
  447. return $rels_xml;
  448. }
  449. protected function buildWorkbookXML()
  450. {
  451. $workbook_xml="";
  452. $workbook_xml.='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n";
  453. $workbook_xml.='<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">';
  454. $workbook_xml.='<fileVersion appName="Calc"/><workbookPr backupFile="false" showObjects="all" date1904="false"/><workbookProtection/>';
  455. $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>';
  456. $workbook_xml.='<sheets>';
  457. foreach($this->sheets_meta as $i=>$sheet_meta) {
  458. $workbook_xml.='<sheet name="'.self::xmlspecialchars($sheet_meta['sheetname']).'" sheetId="'.($i+1).'" state="visible" r:id="rId'.($i+2).'"/>';
  459. }
  460. $workbook_xml.='</sheets>';
  461. $workbook_xml.='<calcPr iterateCount="100" refMode="A1" iterate="false" iterateDelta="0.001"/></workbook>';
  462. return $workbook_xml;
  463. }
  464. protected function buildWorkbookRelsXML()
  465. {
  466. $wkbkrels_xml="";
  467. $wkbkrels_xml.='<?xml version="1.0" encoding="UTF-8"?>'."\n";
  468. $wkbkrels_xml.='<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">';
  469. $wkbkrels_xml.='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>';
  470. foreach($this->sheets_meta as $i=>$sheet_meta) {
  471. $wkbkrels_xml.='<Relationship Id="rId'.($i+2).'" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/'.($sheet_meta['xmlname']).'"/>';
  472. }
  473. if (!empty($this->shared_strings)) {
  474. $wkbkrels_xml.='<Relationship Id="rId'.(count($this->sheets_meta)+2).'" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings" Target="sharedStrings.xml"/>';
  475. }
  476. $wkbkrels_xml.="\n";
  477. $wkbkrels_xml.='</Relationships>';
  478. return $wkbkrels_xml;
  479. }
  480. protected function buildContentTypesXML()
  481. {
  482. $content_types_xml="";
  483. $content_types_xml.='<?xml version="1.0" encoding="UTF-8"?>'."\n";
  484. $content_types_xml.='<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">';
  485. $content_types_xml.='<Override PartName="/_rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
  486. $content_types_xml.='<Override PartName="/xl/_rels/workbook.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
  487. foreach($this->sheets_meta as $i=>$sheet_meta) {
  488. $content_types_xml.='<Override PartName="/xl/worksheets/'.($sheet_meta['xmlname']).'" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
  489. }
  490. if (!empty($this->shared_strings)) {
  491. $content_types_xml.='<Override PartName="/xl/sharedStrings.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml"/>';
  492. }
  493. $content_types_xml.='<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>';
  494. $content_types_xml.='<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>';
  495. $content_types_xml.='<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>';
  496. $content_types_xml.='<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>';
  497. $content_types_xml.="\n";
  498. $content_types_xml.='</Types>';
  499. return $content_types_xml;
  500. }
  501. //------------------------------------------------------------------
  502. /*
  503. * @param $row_number int, zero based
  504. * @param $column_number int, zero based
  505. * @return Cell label/coordinates, ex: A1, C3, AA42
  506. * */
  507. public static function xlsCell($row_number, $column_number)
  508. {
  509. $n = $column_number;
  510. for($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
  511. $r = chr($n%26 + 0x41) . $r;
  512. }
  513. return $r . ($row_number+1);
  514. }
  515. //------------------------------------------------------------------
  516. public static function log($string)
  517. {
  518. file_put_contents("php://stderr", date("Y-m-d H:i:s:").rtrim(is_array($string) ? json_encode($string) : $string)."\n");
  519. }
  520. //------------------------------------------------------------------
  521. public static function xmlspecialchars($val)
  522. {
  523. return str_replace("'", "&#39;", htmlspecialchars($val));
  524. }
  525. //------------------------------------------------------------------
  526. public static function array_first_key(array $arr)
  527. {
  528. reset($arr);
  529. $first_key = key($arr);
  530. return $first_key;
  531. }
  532. //------------------------------------------------------------------
  533. public static function convert_date_time($date_input) //thanks to Excel::Writer::XLSX::Worksheet.pm (perl)
  534. {
  535. $days = 0; # Number of days since epoch
  536. $seconds = 0; # Time expressed as fraction of 24h hours in seconds
  537. $year=$month=$day=0;
  538. $hour=$min =$sec=0;
  539. $date_time = $date_input;
  540. if (preg_match("/(\d{4})\-(\d{2})\-(\d{2})/", $date_time, $matches))
  541. {
  542. list($junk,$year,$month,$day) = $matches;
  543. }
  544. if (preg_match("/(\d{2}):(\d{2}):(\d{2})/", $date_time, $matches))
  545. {
  546. list($junk,$hour,$min,$sec) = $matches;
  547. $seconds = ( $hour * 60 * 60 + $min * 60 + $sec ) / ( 24 * 60 * 60 );
  548. }
  549. //using 1900 as epoch, not 1904, ignoring 1904 special case
  550. # Special cases for Excel.
  551. if ("$year-$month-$day"=='1899-12-31') return $seconds ; # Excel 1900 epoch
  552. if ("$year-$month-$day"=='1900-01-00') return $seconds ; # Excel 1900 epoch
  553. if ("$year-$month-$day"=='1900-02-29') return 60 + $seconds ; # Excel false leapday
  554. # We calculate the date by calculating the number of days since the epoch
  555. # and adjust for the number of leap days. We calculate the number of leap
  556. # days by normalising the year in relation to the epoch. Thus the year 2000
  557. # becomes 100 for 4 and 100 year leapdays and 400 for 400 year leapdays.
  558. $epoch = 1900;
  559. $offset = 0;
  560. $norm = 300;
  561. $range = $year - $epoch;
  562. # Set month days and check for leap year.
  563. $leap = (($year % 400 == 0) || (($year % 4 == 0) && ($year % 100)) ) ? 1 : 0;
  564. $mdays = array( 31, ($leap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
  565. # Some boundary checks
  566. if($year < $epoch || $year > 9999) return 0;
  567. if($month < 1 || $month > 12) return 0;
  568. if($day < 1 || $day > $mdays[ $month - 1 ]) return 0;
  569. # Accumulate the number of days since the epoch.
  570. $days = $day; # Add days for current month
  571. $days += array_sum( array_slice($mdays, 0, $month-1 ) ); # Add days for past months
  572. $days += $range * 365; # Add days for past years
  573. $days += intval( ( $range ) / 4 ); # Add leapdays
  574. $days -= intval( ( $range + $offset ) / 100 ); # Subtract 100 year leapdays
  575. $days += intval( ( $range + $offset + $norm ) / 400 ); # Add 400 year leapdays
  576. $days -= $leap; # Already counted above
  577. # Adjust for Excel erroneously treating 1900 as a leap year.
  578. if ($days > 59) { $days++;}
  579. return $days + $seconds;
  580. }
  581. //------------------------------------------------------------------
  582. }