新版订单消耗系统

XLSXWriter.php 48KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. <?php
  2. /*
  3. * @license MIT License
  4. * */
  5. namespace App\libs\XLSXWriter;
  6. class XLSXWriter
  7. {
  8. //http://www.ecma-international.org/publications/standards/Ecma-376.htm
  9. //http://officeopenxml.com/SSstyles.php
  10. //------------------------------------------------------------------
  11. //http://office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP010073849.aspx
  12. const EXCEL_2007_MAX_ROW=1048576;
  13. const EXCEL_2007_MAX_COL=16384;
  14. //------------------------------------------------------------------
  15. protected $title;
  16. protected $subject;
  17. protected $author;
  18. protected $isRightToLeft;
  19. protected $company;
  20. protected $description;
  21. protected $keywords = array();
  22. protected $current_sheet;
  23. protected $sheets = array();
  24. protected $temp_files = array();
  25. protected $cell_styles = array();
  26. protected $number_formats = array();
  27. public function __construct()
  28. {
  29. defined('ENT_XML1') or define('ENT_XML1',16);//for php 5.3, avoid fatal error
  30. date_default_timezone_get() or date_default_timezone_set('UTC');//php.ini missing tz, avoid warning
  31. is_writeable($this->tempFilename()) or self::log("Warning: tempdir ".sys_get_temp_dir()." not writeable, use ->setTempDir()");
  32. class_exists('ZipArchive') or self::log("Error: ZipArchive class does not exist");
  33. $this->addCellStyle($number_format='GENERAL', $style_string=null);
  34. }
  35. public function setTitle($title='') { $this->title=$title; }
  36. public function setSubject($subject='') { $this->subject=$subject; }
  37. public function setAuthor($author='') { $this->author=$author; }
  38. public function setCompany($company='') { $this->company=$company; }
  39. public function setKeywords($keywords='') { $this->keywords=$keywords; }
  40. public function setDescription($description='') { $this->description=$description; }
  41. public function setTempDir($tempdir='') { $this->tempdir=$tempdir; }
  42. public function setRightToLeft($isRightToLeft=false){ $this->isRightToLeft=$isRightToLeft; }
  43. public function __destruct()
  44. {
  45. if (!empty($this->temp_files)) {
  46. foreach($this->temp_files as $temp_file) {
  47. @unlink($temp_file);
  48. }
  49. }
  50. }
  51. protected function tempFilename()
  52. {
  53. $tempdir = !empty($this->tempdir) ? $this->tempdir : sys_get_temp_dir();
  54. $filename = tempnam($tempdir, "xlsx_writer_");
  55. if (!$filename) {
  56. // If you are seeing this error, it's possible you may have too many open
  57. // file handles. If you're creating a spreadsheet with many small inserts,
  58. // it is possible to exceed the default 1024 open file handles. Run 'ulimit -a'
  59. // and try increasing the 'open files' number with 'ulimit -n 8192'
  60. throw new \Exception("Unable to create tempfile - check file handle limits?");
  61. }
  62. $this->temp_files[] = $filename;
  63. return $filename;
  64. }
  65. public function writeToStdOut()
  66. {
  67. $temp_file = $this->tempFilename();
  68. self::writeToFile($temp_file);
  69. readfile($temp_file);
  70. }
  71. public function writeToString()
  72. {
  73. $temp_file = $this->tempFilename();
  74. self::writeToFile($temp_file);
  75. $string = file_get_contents($temp_file);
  76. return $string;
  77. }
  78. public function writeToFile($filename)
  79. {
  80. foreach($this->sheets as $sheet_name => $sheet) {
  81. self::finalizeSheet($sheet_name);//making sure all footers have been written
  82. }
  83. if ( file_exists( $filename ) ) {
  84. if ( is_writable( $filename ) ) {
  85. @unlink( $filename ); //if the zip already exists, remove it
  86. } else {
  87. self::log( "Error in " . __CLASS__ . "::" . __FUNCTION__ . ", file is not writeable." );
  88. return;
  89. }
  90. }
  91. $zip = new \ZipArchive();
  92. if (empty($this->sheets)) { self::log("Error in ".__CLASS__."::".__FUNCTION__.", no worksheets defined."); return; }
  93. if (!$zip->open($filename, \ZipArchive::CREATE)) { self::log("Error in ".__CLASS__."::".__FUNCTION__.", unable to create zip."); return; }
  94. $zip->addEmptyDir("docProps/");
  95. $zip->addFromString("docProps/app.xml" , self::buildAppXML() );
  96. $zip->addFromString("docProps/core.xml", self::buildCoreXML());
  97. $zip->addEmptyDir("_rels/");
  98. $zip->addFromString("_rels/.rels", self::buildRelationshipsXML());
  99. $zip->addEmptyDir("xl/worksheets/");
  100. foreach($this->sheets as $sheet) {
  101. $zip->addFile($sheet->filename, "xl/worksheets/".$sheet->xmlname );
  102. }
  103. $zip->addFromString("xl/workbook.xml" , self::buildWorkbookXML() );
  104. $zip->addFile($this->writeStylesXML(), "xl/styles.xml" ); //$zip->addFromString("xl/styles.xml" , self::buildStylesXML() );
  105. $zip->addFromString("[Content_Types].xml" , self::buildContentTypesXML() );
  106. $zip->addEmptyDir("xl/_rels/");
  107. $zip->addFromString("xl/_rels/workbook.xml.rels", self::buildWorkbookRelsXML() );
  108. $zip->close();
  109. }
  110. protected function initializeSheet($sheet_name, $col_widths=array(), $auto_filter=false, $freeze_rows=false, $freeze_columns=false )
  111. {
  112. //if already initialized
  113. if ($this->current_sheet==$sheet_name || isset($this->sheets[$sheet_name]))
  114. return;
  115. $sheet_filename = $this->tempFilename();
  116. $sheet_xmlname = 'sheet' . (count($this->sheets) + 1).".xml";
  117. $this->sheets[$sheet_name] = (object)array(
  118. 'filename' => $sheet_filename,
  119. 'sheetname' => $sheet_name,
  120. 'xmlname' => $sheet_xmlname,
  121. 'row_count' => 0,
  122. 'file_writer' => new XLSXWriterBuffererWriter($sheet_filename),
  123. 'columns' => array(),
  124. 'merge_cells' => array(),
  125. 'max_cell_tag_start' => 0,
  126. 'max_cell_tag_end' => 0,
  127. 'auto_filter' => $auto_filter,
  128. 'freeze_rows' => $freeze_rows,
  129. 'freeze_columns' => $freeze_columns,
  130. 'finalized' => false,
  131. );
  132. $rightToLeftValue = $this->isRightToLeft ? 'true' : 'false';
  133. $sheet = &$this->sheets[$sheet_name];
  134. $tabselected = count($this->sheets) == 1 ? 'true' : 'false';//only first sheet is selected
  135. $max_cell=XLSXWriter::xlsCell(self::EXCEL_2007_MAX_ROW, self::EXCEL_2007_MAX_COL);//XFE1048577
  136. $sheet->file_writer->write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . "\n");
  137. $sheet->file_writer->write('<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">');
  138. $sheet->file_writer->write( '<sheetPr filterMode="false">');
  139. $sheet->file_writer->write( '<pageSetUpPr fitToPage="false"/>');
  140. $sheet->file_writer->write( '</sheetPr>');
  141. $sheet->max_cell_tag_start = $sheet->file_writer->ftell();
  142. $sheet->file_writer->write('<dimension ref="A1:' . $max_cell . '"/>');
  143. $sheet->max_cell_tag_end = $sheet->file_writer->ftell();
  144. $sheet->file_writer->write( '<sheetViews>');
  145. $sheet->file_writer->write( '<sheetView colorId="64" defaultGridColor="true" rightToLeft="'.$rightToLeftValue.'" 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">');
  146. if ($sheet->freeze_rows && $sheet->freeze_columns) {
  147. $sheet->file_writer->write( '<pane ySplit="'.$sheet->freeze_rows.'" xSplit="'.$sheet->freeze_columns.'" topLeftCell="'.self::xlsCell($sheet->freeze_rows, $sheet->freeze_columns).'" activePane="bottomRight" state="frozen"/>');
  148. $sheet->file_writer->write( '<selection activeCell="'.self::xlsCell($sheet->freeze_rows, 0).'" activeCellId="0" pane="topRight" sqref="'.self::xlsCell($sheet->freeze_rows, 0).'"/>');
  149. $sheet->file_writer->write( '<selection activeCell="'.self::xlsCell(0, $sheet->freeze_columns).'" activeCellId="0" pane="bottomLeft" sqref="'.self::xlsCell(0, $sheet->freeze_columns).'"/>');
  150. $sheet->file_writer->write( '<selection activeCell="'.self::xlsCell($sheet->freeze_rows, $sheet->freeze_columns).'" activeCellId="0" pane="bottomRight" sqref="'.self::xlsCell($sheet->freeze_rows, $sheet->freeze_columns).'"/>');
  151. }
  152. elseif ($sheet->freeze_rows) {
  153. $sheet->file_writer->write( '<pane ySplit="'.$sheet->freeze_rows.'" topLeftCell="'.self::xlsCell($sheet->freeze_rows, 0).'" activePane="bottomLeft" state="frozen"/>');
  154. $sheet->file_writer->write( '<selection activeCell="'.self::xlsCell($sheet->freeze_rows, 0).'" activeCellId="0" pane="bottomLeft" sqref="'.self::xlsCell($sheet->freeze_rows, 0).'"/>');
  155. }
  156. elseif ($sheet->freeze_columns) {
  157. $sheet->file_writer->write( '<pane xSplit="'.$sheet->freeze_columns.'" topLeftCell="'.self::xlsCell(0, $sheet->freeze_columns).'" activePane="topRight" state="frozen"/>');
  158. $sheet->file_writer->write( '<selection activeCell="'.self::xlsCell(0, $sheet->freeze_columns).'" activeCellId="0" pane="topRight" sqref="'.self::xlsCell(0, $sheet->freeze_columns).'"/>');
  159. }
  160. else { // not frozen
  161. $sheet->file_writer->write( '<selection activeCell="A1" activeCellId="0" pane="topLeft" sqref="A1"/>');
  162. }
  163. $sheet->file_writer->write( '</sheetView>');
  164. $sheet->file_writer->write( '</sheetViews>');
  165. $sheet->file_writer->write( '<cols>');
  166. $i=0;
  167. if (!empty($col_widths)) {
  168. foreach($col_widths as $column_width) {
  169. $sheet->file_writer->write( '<col collapsed="false" hidden="false" max="'.($i+1).'" min="'.($i+1).'" style="0" customWidth="true" width="'.floatval($column_width).'"/>');
  170. $i++;
  171. }
  172. }
  173. $sheet->file_writer->write( '<col collapsed="false" hidden="false" max="1024" min="'.($i+1).'" style="0" customWidth="false" width="11.5"/>');
  174. $sheet->file_writer->write( '</cols>');
  175. $sheet->file_writer->write( '<sheetData>');
  176. }
  177. private function addCellStyle($number_format, $cell_style_string)
  178. {
  179. $number_format_idx = self::add_to_list_get_index($this->number_formats, $number_format);
  180. $lookup_string = $number_format_idx.";".$cell_style_string;
  181. $cell_style_idx = self::add_to_list_get_index($this->cell_styles, $lookup_string);
  182. return $cell_style_idx;
  183. }
  184. private function initializeColumnTypes($header_types)
  185. {
  186. $column_types = array();
  187. foreach($header_types as $v)
  188. {
  189. $number_format = self::numberFormatStandardized($v);
  190. $number_format_type = self::determineNumberFormatType($number_format);
  191. $cell_style_idx = $this->addCellStyle($number_format, $style_string=null);
  192. $column_types[] = array('number_format' => $number_format,//contains excel format like 'YYYY-MM-DD HH:MM:SS'
  193. 'number_format_type' => $number_format_type, //contains friendly format like 'datetime'
  194. 'default_cell_style' => $cell_style_idx,
  195. );
  196. }
  197. return $column_types;
  198. }
  199. public function writeSheetHeader($sheet_name, array $header_types, $col_options = null)
  200. {
  201. if (empty($sheet_name) || empty($header_types) || !empty($this->sheets[$sheet_name]))
  202. return;
  203. $suppress_row = isset($col_options['suppress_row']) ? intval($col_options['suppress_row']) : false;
  204. if (is_bool($col_options))
  205. {
  206. self::log( "Warning! passing $suppress_row=false|true to writeSheetHeader() is deprecated, this will be removed in a future version." );
  207. $suppress_row = intval($col_options);
  208. }
  209. $style = &$col_options;
  210. $col_widths = isset($col_options['widths']) ? (array)$col_options['widths'] : array();
  211. $auto_filter = isset($col_options['auto_filter']) ? intval($col_options['auto_filter']) : false;
  212. $freeze_rows = isset($col_options['freeze_rows']) ? intval($col_options['freeze_rows']) : false;
  213. $freeze_columns = isset($col_options['freeze_columns']) ? intval($col_options['freeze_columns']) : false;
  214. $this->initializeSheet($sheet_name, $col_widths, $auto_filter, $freeze_rows, $freeze_columns);
  215. $sheet = &$this->sheets[$sheet_name];
  216. $sheet->columns = $this->initializeColumnTypes($header_types);
  217. if (!$suppress_row)
  218. {
  219. $header_row = array_keys($header_types);
  220. $sheet->file_writer->write('<row collapsed="false" customFormat="false" customHeight="false" hidden="false" ht="12.1" outlineLevel="0" r="' . (1) . '">');
  221. foreach ($header_row as $c => $v) {
  222. $cell_style_idx = empty($style) ? $sheet->columns[$c]['default_cell_style'] : $this->addCellStyle( 'GENERAL', json_encode(isset($style[0]) ? $style[$c] : $style) );
  223. $this->writeCell($sheet->file_writer, 0, $c, $v, $number_format_type='n_string', $cell_style_idx);
  224. }
  225. $sheet->file_writer->write('</row>');
  226. $sheet->row_count++;
  227. }
  228. $this->current_sheet = $sheet_name;
  229. }
  230. public function writeSheetRow($sheet_name, array $row, $row_options=null)
  231. {
  232. if (empty($sheet_name))
  233. return;
  234. $this->initializeSheet($sheet_name);
  235. $sheet = &$this->sheets[$sheet_name];
  236. if (count($sheet->columns) < count($row)) {
  237. $default_column_types = $this->initializeColumnTypes( array_fill($from=0, $until=count($row), 'GENERAL') );//will map to n_auto
  238. $sheet->columns = array_merge((array)$sheet->columns, $default_column_types);
  239. }
  240. if (!empty($row_options))
  241. {
  242. $ht = isset($row_options['height']) ? floatval($row_options['height']) : 12.1;
  243. $customHt = isset($row_options['height']) ? true : false;
  244. $hidden = isset($row_options['hidden']) ? (bool)($row_options['hidden']) : false;
  245. $collapsed = isset($row_options['collapsed']) ? (bool)($row_options['collapsed']) : false;
  246. $sheet->file_writer->write('<row collapsed="'.($collapsed ? 'true' : 'false').'" customFormat="false" customHeight="'.($customHt ? 'true' : 'false').'" hidden="'.($hidden ? 'true' : 'false').'" ht="'.($ht).'" outlineLevel="0" r="' . ($sheet->row_count + 1) . '">');
  247. }
  248. else
  249. {
  250. $sheet->file_writer->write('<row collapsed="false" customFormat="false" customHeight="false" hidden="false" ht="12.1" outlineLevel="0" r="' . ($sheet->row_count + 1) . '">');
  251. }
  252. $style = &$row_options;
  253. $c=0;
  254. foreach ($row as $v) {
  255. $number_format = $sheet->columns[$c]['number_format'];
  256. $number_format_type = $sheet->columns[$c]['number_format_type'];
  257. $cell_style_idx = empty($style) ? $sheet->columns[$c]['default_cell_style'] : $this->addCellStyle( $number_format, json_encode(isset($style[0]) ? $style[$c] : $style) );
  258. $this->writeCell($sheet->file_writer, $sheet->row_count, $c, $v, $number_format_type, $cell_style_idx);
  259. $c++;
  260. }
  261. $sheet->file_writer->write('</row>');
  262. $sheet->row_count++;
  263. $this->current_sheet = $sheet_name;
  264. }
  265. public function countSheetRows($sheet_name = '')
  266. {
  267. $sheet_name = $sheet_name ? $sheet_name : $this->current_sheet;
  268. return array_key_exists($sheet_name, $this->sheets) ? $this->sheets[$sheet_name]->row_count : 0;
  269. }
  270. protected function finalizeSheet($sheet_name)
  271. {
  272. if (empty($sheet_name) || $this->sheets[$sheet_name]->finalized)
  273. return;
  274. $sheet = &$this->sheets[$sheet_name];
  275. $sheet->file_writer->write( '</sheetData>');
  276. if (!empty($sheet->merge_cells)) {
  277. $sheet->file_writer->write( '<mergeCells>');
  278. foreach ($sheet->merge_cells as $range) {
  279. $sheet->file_writer->write( '<mergeCell ref="' . $range . '"/>');
  280. }
  281. $sheet->file_writer->write( '</mergeCells>');
  282. }
  283. $max_cell = self::xlsCell($sheet->row_count - 1, count($sheet->columns) - 1);
  284. if ($sheet->auto_filter) {
  285. $sheet->file_writer->write( '<autoFilter ref="A1:' . $max_cell . '"/>');
  286. }
  287. $sheet->file_writer->write( '<printOptions headings="false" gridLines="false" gridLinesSet="true" horizontalCentered="false" verticalCentered="false"/>');
  288. $sheet->file_writer->write( '<pageMargins left="0.5" right="0.5" top="1.0" bottom="1.0" header="0.5" footer="0.5"/>');
  289. $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"/>');
  290. $sheet->file_writer->write( '<headerFooter differentFirst="false" differentOddEven="false">');
  291. $sheet->file_writer->write( '<oddHeader>&amp;C&amp;&quot;Times New Roman,Regular&quot;&amp;12&amp;A</oddHeader>');
  292. $sheet->file_writer->write( '<oddFooter>&amp;C&amp;&quot;Times New Roman,Regular&quot;&amp;12Page &amp;P</oddFooter>');
  293. $sheet->file_writer->write( '</headerFooter>');
  294. $sheet->file_writer->write('</worksheet>');
  295. $max_cell_tag = '<dimension ref="A1:' . $max_cell . '"/>';
  296. $padding_length = $sheet->max_cell_tag_end - $sheet->max_cell_tag_start - strlen($max_cell_tag);
  297. $sheet->file_writer->fseek($sheet->max_cell_tag_start);
  298. $sheet->file_writer->write($max_cell_tag.str_repeat(" ", $padding_length));
  299. $sheet->file_writer->close();
  300. $sheet->finalized=true;
  301. }
  302. public function markMergedCell($sheet_name, $start_cell_row, $start_cell_column, $end_cell_row, $end_cell_column)
  303. {
  304. if (empty($sheet_name) || $this->sheets[$sheet_name]->finalized)
  305. return;
  306. $this->initializeSheet($sheet_name);
  307. $sheet = &$this->sheets[$sheet_name];
  308. $startCell = self::xlsCell($start_cell_row, $start_cell_column);
  309. $endCell = self::xlsCell($end_cell_row, $end_cell_column);
  310. $sheet->merge_cells[] = $startCell . ":" . $endCell;
  311. }
  312. public function writeSheet(array $data, $sheet_name='', array $header_types=array())
  313. {
  314. $sheet_name = empty($sheet_name) ? 'Sheet1' : $sheet_name;
  315. $data = empty($data) ? array(array('')) : $data;
  316. if (!empty($header_types))
  317. {
  318. $this->writeSheetHeader($sheet_name, $header_types);
  319. }
  320. foreach($data as $i=>$row)
  321. {
  322. $this->writeSheetRow($sheet_name, $row);
  323. }
  324. $this->finalizeSheet($sheet_name);
  325. }
  326. protected function writeCell(XLSXWriterBuffererWriter &$file, $row_number, $column_number, $value, $num_format_type, $cell_style_idx)
  327. {
  328. $cell_name = self::xlsCell($row_number, $column_number);
  329. if (!is_scalar($value) || $value==='') { //objects, array, empty
  330. $file->write('<c r="'.$cell_name.'" s="'.$cell_style_idx.'"/>');
  331. } elseif (is_string($value) && $value[0]=='='){
  332. $file->write('<c r="'.$cell_name.'" s="'.$cell_style_idx.'" t="s"><f>'.self::xmlspecialchars($value).'</f></c>');
  333. } elseif ($num_format_type=='n_date') {
  334. $file->write('<c r="'.$cell_name.'" s="'.$cell_style_idx.'" t="n"><v>'.intval(self::convert_date_time($value)).'</v></c>');
  335. } elseif ($num_format_type=='n_datetime') {
  336. $file->write('<c r="'.$cell_name.'" s="'.$cell_style_idx.'" t="n"><v>'.self::convert_date_time($value).'</v></c>');
  337. } elseif ($num_format_type=='n_numeric') {
  338. $file->write('<c r="'.$cell_name.'" s="'.$cell_style_idx.'" t="n"><v>'.self::xmlspecialchars($value).'</v></c>');//int,float,currency
  339. } elseif ($num_format_type=='n_string') {
  340. $file->write('<c r="'.$cell_name.'" s="'.$cell_style_idx.'" t="inlineStr"><is><t>'.self::xmlspecialchars($value).'</t></is></c>');
  341. } elseif ($num_format_type=='n_auto' || 1) { //auto-detect unknown column types
  342. if (!is_string($value) || $value=='0' || ($value[0]!='0' && ctype_digit($value)) || preg_match("/^\-?(0|[1-9][0-9]*)(\.[0-9]+)?$/", $value)){
  343. $file->write('<c r="'.$cell_name.'" s="'.$cell_style_idx.'" t="n"><v>'.self::xmlspecialchars($value).'</v></c>');//int,float,currency
  344. } else { //implied: ($cell_format=='string')
  345. $file->write('<c r="'.$cell_name.'" s="'.$cell_style_idx.'" t="inlineStr"><is><t>'.self::xmlspecialchars($value).'</t></is></c>');
  346. }
  347. }
  348. }
  349. protected function styleFontIndexes()
  350. {
  351. static $border_allowed = array('left','right','top','bottom');
  352. static $border_style_allowed = array('thin','medium','thick','dashDot','dashDotDot','dashed','dotted','double','hair','mediumDashDot','mediumDashDotDot','mediumDashed','slantDashDot');
  353. static $horizontal_allowed = array('general','left','right','justify','center');
  354. static $vertical_allowed = array('bottom','center','distributed','top');
  355. $default_font = array('size'=>'10','name'=>'Arial','family'=>'2');
  356. $fills = array('','');//2 placeholders for static xml later
  357. $fonts = array('','','','');//4 placeholders for static xml later
  358. $borders = array('');//1 placeholder for static xml later
  359. $style_indexes = array();
  360. foreach($this->cell_styles as $i=>$cell_style_string)
  361. {
  362. $semi_colon_pos = strpos($cell_style_string,";");
  363. $number_format_idx = substr($cell_style_string, 0, $semi_colon_pos);
  364. $style_json_string = substr($cell_style_string, $semi_colon_pos+1);
  365. $style = @json_decode($style_json_string, $as_assoc=true);
  366. $style_indexes[$i] = array('num_fmt_idx'=>$number_format_idx);//initialize entry
  367. if (isset($style['border']) && is_string($style['border']))//border is a comma delimited str
  368. {
  369. $border_value['side'] = array_intersect(explode(",", $style['border']), $border_allowed);
  370. if (isset($style['border-style']) && in_array($style['border-style'],$border_style_allowed))
  371. {
  372. $border_value['style'] = $style['border-style'];
  373. }
  374. if (isset($style['border-color']) && is_string($style['border-color']) && $style['border-color'][0]=='#')
  375. {
  376. $v = substr($style['border-color'],1,6);
  377. $v = strlen($v)==3 ? $v[0].$v[0].$v[1].$v[1].$v[2].$v[2] : $v;// expand cf0 => ccff00
  378. $border_value['color'] = "FF".strtoupper($v);
  379. }
  380. $style_indexes[$i]['border_idx'] = self::add_to_list_get_index($borders, json_encode($border_value));
  381. }
  382. if (isset($style['fill']) && is_string($style['fill']) && $style['fill'][0]=='#')
  383. {
  384. $v = substr($style['fill'],1,6);
  385. $v = strlen($v)==3 ? $v[0].$v[0].$v[1].$v[1].$v[2].$v[2] : $v;// expand cf0 => ccff00
  386. $style_indexes[$i]['fill_idx'] = self::add_to_list_get_index($fills, "FF".strtoupper($v) );
  387. }
  388. if (isset($style['halign']) && in_array($style['halign'],$horizontal_allowed))
  389. {
  390. $style_indexes[$i]['alignment'] = true;
  391. $style_indexes[$i]['halign'] = $style['halign'];
  392. }
  393. if (isset($style['valign']) && in_array($style['valign'],$vertical_allowed))
  394. {
  395. $style_indexes[$i]['alignment'] = true;
  396. $style_indexes[$i]['valign'] = $style['valign'];
  397. }
  398. if (isset($style['wrap_text']))
  399. {
  400. $style_indexes[$i]['alignment'] = true;
  401. $style_indexes[$i]['wrap_text'] = (bool)$style['wrap_text'];
  402. }
  403. $font = $default_font;
  404. if (isset($style['font-size']))
  405. {
  406. $font['size'] = floatval($style['font-size']);//floatval to allow "10.5" etc
  407. }
  408. if (isset($style['font']) && is_string($style['font']))
  409. {
  410. if ($style['font']=='Comic Sans MS') { $font['family']=4; }
  411. if ($style['font']=='Times New Roman') { $font['family']=1; }
  412. if ($style['font']=='Courier New') { $font['family']=3; }
  413. $font['name'] = strval($style['font']);
  414. }
  415. if (isset($style['font-style']) && is_string($style['font-style']))
  416. {
  417. if (strpos($style['font-style'], 'bold')!==false) { $font['bold'] = true; }
  418. if (strpos($style['font-style'], 'italic')!==false) { $font['italic'] = true; }
  419. if (strpos($style['font-style'], 'strike')!==false) { $font['strike'] = true; }
  420. if (strpos($style['font-style'], 'underline')!==false) { $font['underline'] = true; }
  421. }
  422. if (isset($style['color']) && is_string($style['color']) && $style['color'][0]=='#' )
  423. {
  424. $v = substr($style['color'],1,6);
  425. $v = strlen($v)==3 ? $v[0].$v[0].$v[1].$v[1].$v[2].$v[2] : $v;// expand cf0 => ccff00
  426. $font['color'] = "FF".strtoupper($v);
  427. }
  428. if ($font!=$default_font)
  429. {
  430. $style_indexes[$i]['font_idx'] = self::add_to_list_get_index($fonts, json_encode($font) );
  431. }
  432. }
  433. return array('fills'=>$fills,'fonts'=>$fonts,'borders'=>$borders,'styles'=>$style_indexes );
  434. }
  435. protected function writeStylesXML()
  436. {
  437. $r = self::styleFontIndexes();
  438. $fills = $r['fills'];
  439. $fonts = $r['fonts'];
  440. $borders = $r['borders'];
  441. $style_indexes = $r['styles'];
  442. $temporary_filename = $this->tempFilename();
  443. $file = new XLSXWriterBuffererWriter($temporary_filename);
  444. $file->write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n");
  445. $file->write('<styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">');
  446. $file->write('<numFmts count="'.count($this->number_formats).'">');
  447. foreach($this->number_formats as $i=>$v) {
  448. $file->write('<numFmt numFmtId="'.(164+$i).'" formatCode="'.self::xmlspecialchars($v).'" />');
  449. }
  450. //$file->write( '<numFmt formatCode="GENERAL" numFmtId="164"/>');
  451. //$file->write( '<numFmt formatCode="[$$-1009]#,##0.00;[RED]\-[$$-1009]#,##0.00" numFmtId="165"/>');
  452. //$file->write( '<numFmt formatCode="YYYY-MM-DD\ HH:MM:SS" numFmtId="166"/>');
  453. //$file->write( '<numFmt formatCode="YYYY-MM-DD" numFmtId="167"/>');
  454. $file->write('</numFmts>');
  455. $file->write('<fonts count="'.(count($fonts)).'">');
  456. $file->write( '<font><name val="Arial"/><charset val="1"/><family val="2"/><sz val="10"/></font>');
  457. $file->write( '<font><name val="Arial"/><family val="0"/><sz val="10"/></font>');
  458. $file->write( '<font><name val="Arial"/><family val="0"/><sz val="10"/></font>');
  459. $file->write( '<font><name val="Arial"/><family val="0"/><sz val="10"/></font>');
  460. foreach($fonts as $font) {
  461. if (!empty($font)) { //fonts have 4 empty placeholders in array to offset the 4 static xml entries above
  462. $f = json_decode($font,true);
  463. $file->write('<font>');
  464. $file->write( '<name val="'.htmlspecialchars($f['name']).'"/><charset val="1"/><family val="'.intval($f['family']).'"/>');
  465. $file->write( '<sz val="'.intval($f['size']).'"/>');
  466. if (!empty($f['color'])) { $file->write('<color rgb="'.strval($f['color']).'"/>'); }
  467. if (!empty($f['bold'])) { $file->write('<b val="true"/>'); }
  468. if (!empty($f['italic'])) { $file->write('<i val="true"/>'); }
  469. if (!empty($f['underline'])) { $file->write('<u val="single"/>'); }
  470. if (!empty($f['strike'])) { $file->write('<strike val="true"/>'); }
  471. $file->write('</font>');
  472. }
  473. }
  474. $file->write('</fonts>');
  475. $file->write('<fills count="'.(count($fills)).'">');
  476. $file->write( '<fill><patternFill patternType="none"/></fill>');
  477. $file->write( '<fill><patternFill patternType="gray125"/></fill>');
  478. foreach($fills as $fill) {
  479. if (!empty($fill)) { //fills have 2 empty placeholders in array to offset the 2 static xml entries above
  480. $file->write('<fill><patternFill patternType="solid"><fgColor rgb="'.strval($fill).'"/><bgColor indexed="64"/></patternFill></fill>');
  481. }
  482. }
  483. $file->write('</fills>');
  484. $file->write('<borders count="'.(count($borders)).'">');
  485. $file->write( '<border diagonalDown="false" diagonalUp="false"><left/><right/><top/><bottom/><diagonal/></border>');
  486. foreach($borders as $border) {
  487. if (!empty($border)) { //fonts have an empty placeholder in the array to offset the static xml entry above
  488. $pieces = json_decode($border,true);
  489. $border_style = !empty($pieces['style']) ? $pieces['style'] : 'hair';
  490. $border_color = !empty($pieces['color']) ? '<color rgb="'.strval($pieces['color']).'"/>' : '';
  491. $file->write('<border diagonalDown="false" diagonalUp="false">');
  492. foreach (array('left', 'right', 'top', 'bottom') as $side)
  493. {
  494. $show_side = in_array($side,$pieces['side']) ? true : false;
  495. $file->write($show_side ? "<$side style=\"$border_style\">$border_color</$side>" : "<$side/>");
  496. }
  497. $file->write( '<diagonal/>');
  498. $file->write('</border>');
  499. }
  500. }
  501. $file->write('</borders>');
  502. $file->write('<cellStyleXfs count="20">');
  503. $file->write( '<xf applyAlignment="true" applyBorder="true" applyFont="true" applyProtection="true" borderId="0" fillId="0" fontId="0" numFmtId="164">');
  504. $file->write( '<alignment horizontal="general" indent="0" shrinkToFit="false" textRotation="0" vertical="bottom" wrapText="false"/>');
  505. $file->write( '<protection hidden="false" locked="true"/>');
  506. $file->write( '</xf>');
  507. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="0"/>');
  508. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="0"/>');
  509. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="2" numFmtId="0"/>');
  510. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="2" numFmtId="0"/>');
  511. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  512. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  513. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  514. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  515. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  516. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  517. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  518. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  519. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  520. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="0"/>');
  521. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="43"/>');
  522. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="41"/>');
  523. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="44"/>');
  524. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="42"/>');
  525. $file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="true" applyProtection="false" borderId="0" fillId="0" fontId="1" numFmtId="9"/>');
  526. $file->write('</cellStyleXfs>');
  527. $file->write('<cellXfs count="'.(count($style_indexes)).'">');
  528. //$file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="164" xfId="0"/>');
  529. //$file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="165" xfId="0"/>');
  530. //$file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="166" xfId="0"/>');
  531. //$file->write( '<xf applyAlignment="false" applyBorder="false" applyFont="false" applyProtection="false" borderId="0" fillId="0" fontId="0" numFmtId="167" xfId="0"/>');
  532. foreach($style_indexes as $v)
  533. {
  534. $applyAlignment = isset($v['alignment']) ? 'true' : 'false';
  535. $wrapText = !empty($v['wrap_text']) ? 'true' : 'false';
  536. $horizAlignment = isset($v['halign']) ? $v['halign'] : 'general';
  537. $vertAlignment = isset($v['valign']) ? $v['valign'] : 'bottom';
  538. $applyBorder = isset($v['border_idx']) ? 'true' : 'false';
  539. $applyFont = 'true';
  540. $borderIdx = isset($v['border_idx']) ? intval($v['border_idx']) : 0;
  541. $fillIdx = isset($v['fill_idx']) ? intval($v['fill_idx']) : 0;
  542. $fontIdx = isset($v['font_idx']) ? intval($v['font_idx']) : 0;
  543. //$file->write('<xf applyAlignment="'.$applyAlignment.'" applyBorder="'.$applyBorder.'" applyFont="'.$applyFont.'" applyProtection="false" borderId="'.($borderIdx).'" fillId="'.($fillIdx).'" fontId="'.($fontIdx).'" numFmtId="'.(164+$v['num_fmt_idx']).'" xfId="0"/>');
  544. $file->write('<xf applyAlignment="'.$applyAlignment.'" applyBorder="'.$applyBorder.'" applyFont="'.$applyFont.'" applyProtection="false" borderId="'.($borderIdx).'" fillId="'.($fillIdx).'" fontId="'.($fontIdx).'" numFmtId="'.(164+$v['num_fmt_idx']).'" xfId="0">');
  545. $file->write(' <alignment horizontal="'.$horizAlignment.'" vertical="'.$vertAlignment.'" textRotation="0" wrapText="'.$wrapText.'" indent="0" shrinkToFit="false"/>');
  546. $file->write(' <protection locked="true" hidden="false"/>');
  547. $file->write('</xf>');
  548. }
  549. $file->write('</cellXfs>');
  550. $file->write( '<cellStyles count="6">');
  551. $file->write( '<cellStyle builtinId="0" customBuiltin="false" name="Normal" xfId="0"/>');
  552. $file->write( '<cellStyle builtinId="3" customBuiltin="false" name="Comma" xfId="15"/>');
  553. $file->write( '<cellStyle builtinId="6" customBuiltin="false" name="Comma [0]" xfId="16"/>');
  554. $file->write( '<cellStyle builtinId="4" customBuiltin="false" name="Currency" xfId="17"/>');
  555. $file->write( '<cellStyle builtinId="7" customBuiltin="false" name="Currency [0]" xfId="18"/>');
  556. $file->write( '<cellStyle builtinId="5" customBuiltin="false" name="Percent" xfId="19"/>');
  557. $file->write( '</cellStyles>');
  558. $file->write('</styleSheet>');
  559. $file->close();
  560. return $temporary_filename;
  561. }
  562. protected function buildAppXML()
  563. {
  564. $app_xml="";
  565. $app_xml.='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n";
  566. $app_xml.='<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/extended-properties" xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">';
  567. $app_xml.='<TotalTime>0</TotalTime>';
  568. $app_xml.='<Company>'.self::xmlspecialchars($this->company).'</Company>';
  569. $app_xml.='</Properties>';
  570. return $app_xml;
  571. }
  572. protected function buildCoreXML()
  573. {
  574. $core_xml="";
  575. $core_xml.='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n";
  576. $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">';
  577. $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';
  578. $core_xml.='<dc:title>'.self::xmlspecialchars($this->title).'</dc:title>';
  579. $core_xml.='<dc:subject>'.self::xmlspecialchars($this->subject).'</dc:subject>';
  580. $core_xml.='<dc:creator>'.self::xmlspecialchars($this->author).'</dc:creator>';
  581. if (!empty($this->keywords)) {
  582. $core_xml.='<cp:keywords>'.self::xmlspecialchars(implode (", ", (array)$this->keywords)).'</cp:keywords>';
  583. }
  584. $core_xml.='<dc:description>'.self::xmlspecialchars($this->description).'</dc:description>';
  585. $core_xml.='<cp:revision>0</cp:revision>';
  586. $core_xml.='</cp:coreProperties>';
  587. return $core_xml;
  588. }
  589. protected function buildRelationshipsXML()
  590. {
  591. $rels_xml="";
  592. $rels_xml.='<?xml version="1.0" encoding="UTF-8"?>'."\n";
  593. $rels_xml.='<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">';
  594. $rels_xml.='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>';
  595. $rels_xml.='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>';
  596. $rels_xml.='<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/>';
  597. $rels_xml.="\n";
  598. $rels_xml.='</Relationships>';
  599. return $rels_xml;
  600. }
  601. protected function buildWorkbookXML()
  602. {
  603. $i=0;
  604. $workbook_xml="";
  605. $workbook_xml.='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'."\n";
  606. $workbook_xml.='<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">';
  607. $workbook_xml.='<fileVersion appName="Calc"/><workbookPr backupFile="false" showObjects="all" date1904="false"/><workbookProtection/>';
  608. $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>';
  609. $workbook_xml.='<sheets>';
  610. foreach($this->sheets as $sheet_name=>$sheet) {
  611. $sheetname = self::sanitize_sheetname($sheet->sheetname);
  612. $workbook_xml.='<sheet name="'.self::xmlspecialchars($sheetname).'" sheetId="'.($i+1).'" state="visible" r:id="rId'.($i+2).'"/>';
  613. $i++;
  614. }
  615. $workbook_xml.='</sheets>';
  616. $workbook_xml.='<definedNames>';
  617. foreach($this->sheets as $sheet_name=>$sheet) {
  618. if ($sheet->auto_filter) {
  619. $sheetname = self::sanitize_sheetname($sheet->sheetname);
  620. $workbook_xml.='<definedName name="_xlnm._FilterDatabase" localSheetId="0" hidden="1">\''.self::xmlspecialchars($sheetname).'\'!$A$1:' . self::xlsCell($sheet->row_count - 1, count($sheet->columns) - 1, true) . '</definedName>';
  621. $i++;
  622. }
  623. }
  624. $workbook_xml.='</definedNames>';
  625. $workbook_xml.='<calcPr iterateCount="100" refMode="A1" iterate="false" iterateDelta="0.001"/></workbook>';
  626. return $workbook_xml;
  627. }
  628. protected function buildWorkbookRelsXML()
  629. {
  630. $i=0;
  631. $wkbkrels_xml="";
  632. $wkbkrels_xml.='<?xml version="1.0" encoding="UTF-8"?>'."\n";
  633. $wkbkrels_xml.='<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">';
  634. $wkbkrels_xml.='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>';
  635. foreach($this->sheets as $sheet_name=>$sheet) {
  636. $wkbkrels_xml.='<Relationship Id="rId'.($i+2).'" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/'.($sheet->xmlname).'"/>';
  637. $i++;
  638. }
  639. $wkbkrels_xml.="\n";
  640. $wkbkrels_xml.='</Relationships>';
  641. return $wkbkrels_xml;
  642. }
  643. protected function buildContentTypesXML()
  644. {
  645. $content_types_xml="";
  646. $content_types_xml.='<?xml version="1.0" encoding="UTF-8"?>'."\n";
  647. $content_types_xml.='<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">';
  648. $content_types_xml.='<Override PartName="/_rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
  649. $content_types_xml.='<Override PartName="/xl/_rels/workbook.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>';
  650. foreach($this->sheets as $sheet_name=>$sheet) {
  651. $content_types_xml.='<Override PartName="/xl/worksheets/'.($sheet->xmlname).'" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>';
  652. }
  653. $content_types_xml.='<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>';
  654. $content_types_xml.='<Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/>';
  655. $content_types_xml.='<Override PartName="/docProps/app.xml" ContentType="application/vnd.openxmlformats-officedocument.extended-properties+xml"/>';
  656. $content_types_xml.='<Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>';
  657. $content_types_xml.="\n";
  658. $content_types_xml.='</Types>';
  659. return $content_types_xml;
  660. }
  661. //------------------------------------------------------------------
  662. /*
  663. * @param $row_number int, zero based
  664. * @param $column_number int, zero based
  665. * @param $absolute bool
  666. * @return Cell label/coordinates, ex: A1, C3, AA42 (or if $absolute==true: $A$1, $C$3, $AA$42)
  667. * */
  668. public static function xlsCell($row_number, $column_number, $absolute=false)
  669. {
  670. $n = $column_number;
  671. for($r = ""; $n >= 0; $n = intval($n / 26) - 1) {
  672. $r = chr($n%26 + 0x41) . $r;
  673. }
  674. if ($absolute) {
  675. return '$' . $r . '$' . ($row_number+1);
  676. }
  677. return $r . ($row_number+1);
  678. }
  679. //------------------------------------------------------------------
  680. public static function log($string)
  681. {
  682. //file_put_contents("php://stderr", date("Y-m-d H:i:s:").rtrim(is_array($string) ? json_encode($string) : $string)."\n");
  683. error_log(date("Y-m-d H:i:s:").rtrim(is_array($string) ? json_encode($string) : $string)."\n");
  684. }
  685. //------------------------------------------------------------------
  686. public static function sanitize_filename($filename) //http://msdn.microsoft.com/en-us/library/aa365247%28VS.85%29.aspx
  687. {
  688. $nonprinting = array_map('chr', range(0,31));
  689. $invalid_chars = array('<', '>', '?', '"', ':', '|', '\\', '/', '*', '&');
  690. $all_invalids = array_merge($nonprinting,$invalid_chars);
  691. return str_replace($all_invalids, "", $filename);
  692. }
  693. //------------------------------------------------------------------
  694. public static function sanitize_sheetname($sheetname)
  695. {
  696. static $badchars = '\\/?*:[]';
  697. static $goodchars = ' ';
  698. $sheetname = strtr($sheetname, $badchars, $goodchars);
  699. $sheetname = function_exists('mb_substr') ? mb_substr($sheetname, 0, 31) : substr($sheetname, 0, 31);
  700. $sheetname = trim(trim(trim($sheetname),"'"));//trim before and after trimming single quotes
  701. return !empty($sheetname) ? $sheetname : 'Sheet'.((rand()%900)+100);
  702. }
  703. //------------------------------------------------------------------
  704. public static function xmlspecialchars($val)
  705. {
  706. //note, badchars does not include \t\n\r (\x09\x0a\x0d)
  707. static $badchars = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x7f";
  708. static $goodchars = " ";
  709. return strtr(htmlspecialchars($val, ENT_QUOTES | ENT_XML1), $badchars, $goodchars);//strtr appears to be faster than str_replace
  710. }
  711. //------------------------------------------------------------------
  712. public static function array_first_key(array $arr)
  713. {
  714. reset($arr);
  715. $first_key = key($arr);
  716. return $first_key;
  717. }
  718. //------------------------------------------------------------------
  719. private static function determineNumberFormatType($num_format)
  720. {
  721. $num_format = preg_replace("/\[(Black|Blue|Cyan|Green|Magenta|Red|White|Yellow)\]/i", "", $num_format);
  722. if ($num_format=='GENERAL') return 'n_auto';
  723. if ($num_format=='@') return 'n_string';
  724. if ($num_format=='0') return 'n_numeric';
  725. if (preg_match('/[H]{1,2}:[M]{1,2}(?![^"]*+")/i', $num_format)) return 'n_datetime';
  726. if (preg_match('/[M]{1,2}:[S]{1,2}(?![^"]*+")/i', $num_format)) return 'n_datetime';
  727. if (preg_match('/[Y]{2,4}(?![^"]*+")/i', $num_format)) return 'n_date';
  728. if (preg_match('/[D]{1,2}(?![^"]*+")/i', $num_format)) return 'n_date';
  729. if (preg_match('/[M]{1,2}(?![^"]*+")/i', $num_format)) return 'n_date';
  730. if (preg_match('/$(?![^"]*+")/', $num_format)) return 'n_numeric';
  731. if (preg_match('/%(?![^"]*+")/', $num_format)) return 'n_numeric';
  732. if (preg_match('/0(?![^"]*+")/', $num_format)) return 'n_numeric';
  733. return 'n_auto';
  734. }
  735. //------------------------------------------------------------------
  736. private static function numberFormatStandardized($num_format)
  737. {
  738. if ($num_format=='money') { $num_format='dollar'; }
  739. if ($num_format=='number') { $num_format='integer'; }
  740. if ($num_format=='string') $num_format='@';
  741. else if ($num_format=='integer') $num_format='0';
  742. else if ($num_format=='date') $num_format='YYYY-MM-DD';
  743. else if ($num_format=='datetime') $num_format='YYYY-MM-DD HH:MM:SS';
  744. else if ($num_format=='time') $num_format='HH:MM:SS';
  745. else if ($num_format=='price') $num_format='#,##0.00';
  746. else if ($num_format=='dollar') $num_format='[$$-1009]#,##0.00;[RED]-[$$-1009]#,##0.00';
  747. else if ($num_format=='euro') $num_format='#,##0.00 [$€-407];[RED]-#,##0.00 [$€-407]';
  748. $ignore_until='';
  749. $escaped = '';
  750. for($i=0,$ix=strlen($num_format); $i<$ix; $i++)
  751. {
  752. $c = $num_format[$i];
  753. if ($ignore_until=='' && $c=='[')
  754. $ignore_until=']';
  755. else if ($ignore_until=='' && $c=='"')
  756. $ignore_until='"';
  757. else if ($ignore_until==$c)
  758. $ignore_until='';
  759. if ($ignore_until=='' && ($c==' ' || $c=='-' || $c=='(' || $c==')') && ($i==0 || $num_format[$i-1]!='_'))
  760. $escaped.= "\\".$c;
  761. else
  762. $escaped.= $c;
  763. }
  764. return $escaped;
  765. }
  766. //------------------------------------------------------------------
  767. public static function add_to_list_get_index(&$haystack, $needle)
  768. {
  769. $existing_idx = array_search($needle, $haystack, $strict=true);
  770. if ($existing_idx===false)
  771. {
  772. $existing_idx = count($haystack);
  773. $haystack[] = $needle;
  774. }
  775. return $existing_idx;
  776. }
  777. //------------------------------------------------------------------
  778. public static function convert_date_time($date_input) //thanks to Excel::Writer::XLSX::Worksheet.pm (perl)
  779. {
  780. $days = 0; # Number of days since epoch
  781. $seconds = 0; # Time expressed as fraction of 24h hours in seconds
  782. $year=$month=$day=0;
  783. $hour=$min =$sec=0;
  784. $date_time = $date_input;
  785. if (preg_match("/(\d{4})\-(\d{2})\-(\d{2})/", $date_time, $matches))
  786. {
  787. list($junk,$year,$month,$day) = $matches;
  788. }
  789. if (preg_match("/(\d+):(\d{2}):(\d{2})/", $date_time, $matches))
  790. {
  791. list($junk,$hour,$min,$sec) = $matches;
  792. $seconds = ( $hour * 60 * 60 + $min * 60 + $sec ) / ( 24 * 60 * 60 );
  793. }
  794. //using 1900 as epoch, not 1904, ignoring 1904 special case
  795. # Special cases for Excel.
  796. if ("$year-$month-$day"=='1899-12-31') return $seconds ; # Excel 1900 epoch
  797. if ("$year-$month-$day"=='1900-01-00') return $seconds ; # Excel 1900 epoch
  798. if ("$year-$month-$day"=='1900-02-29') return 60 + $seconds ; # Excel false leapday
  799. # We calculate the date by calculating the number of days since the epoch
  800. # and adjust for the number of leap days. We calculate the number of leap
  801. # days by normalising the year in relation to the epoch. Thus the year 2000
  802. # becomes 100 for 4 and 100 year leapdays and 400 for 400 year leapdays.
  803. $epoch = 1900;
  804. $offset = 0;
  805. $norm = 300;
  806. $range = $year - $epoch;
  807. # Set month days and check for leap year.
  808. $leap = (($year % 400 == 0) || (($year % 4 == 0) && ($year % 100)) ) ? 1 : 0;
  809. $mdays = array( 31, ($leap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
  810. # Some boundary checks
  811. if ($year!=0 || $month !=0 || $day!=0)
  812. {
  813. if($year < $epoch || $year > 9999) return 0;
  814. if($month < 1 || $month > 12) return 0;
  815. if($day < 1 || $day > $mdays[ $month - 1 ]) return 0;
  816. }
  817. # Accumulate the number of days since the epoch.
  818. $days = $day; # Add days for current month
  819. $days += array_sum( array_slice($mdays, 0, $month-1 ) ); # Add days for past months
  820. $days += $range * 365; # Add days for past years
  821. $days += intval( ( $range ) / 4 ); # Add leapdays
  822. $days -= intval( ( $range + $offset ) / 100 ); # Subtract 100 year leapdays
  823. $days += intval( ( $range + $offset + $norm ) / 400 ); # Add 400 year leapdays
  824. $days -= $leap; # Already counted above
  825. # Adjust for Excel erroneously treating 1900 as a leap year.
  826. if ($days > 59) { $days++;}
  827. return $days + $seconds;
  828. }
  829. //------------------------------------------------------------------
  830. }
  831. class XLSXWriterBuffererWriter
  832. {
  833. protected $fd=null;
  834. protected $buffer='';
  835. protected $check_utf8=false;
  836. public function __construct($filename, $fd_fopen_flags='w', $check_utf8=false)
  837. {
  838. $this->check_utf8 = $check_utf8;
  839. $this->fd = fopen($filename, $fd_fopen_flags);
  840. if ($this->fd===false) {
  841. XLSXWriter::log("Unable to open $filename for writing.");
  842. }
  843. }
  844. public function write($string)
  845. {
  846. $this->buffer.=$string;
  847. if (isset($this->buffer[8191])) {
  848. $this->purge();
  849. }
  850. }
  851. protected function purge()
  852. {
  853. if ($this->fd) {
  854. if ($this->check_utf8 && !self::isValidUTF8($this->buffer)) {
  855. XLSXWriter::log("Error, invalid UTF8 encoding detected.");
  856. $this->check_utf8 = false;
  857. }
  858. fwrite($this->fd, $this->buffer);
  859. $this->buffer='';
  860. }
  861. }
  862. public function close()
  863. {
  864. $this->purge();
  865. if ($this->fd) {
  866. fclose($this->fd);
  867. $this->fd=null;
  868. }
  869. }
  870. public function __destruct()
  871. {
  872. $this->close();
  873. }
  874. public function ftell()
  875. {
  876. if ($this->fd) {
  877. $this->purge();
  878. return ftell($this->fd);
  879. }
  880. return -1;
  881. }
  882. public function fseek($pos)
  883. {
  884. if ($this->fd) {
  885. $this->purge();
  886. return fseek($this->fd, $pos);
  887. }
  888. return -1;
  889. }
  890. protected static function isValidUTF8($string)
  891. {
  892. if (function_exists('mb_check_encoding'))
  893. {
  894. return mb_check_encoding($string, 'UTF-8') ? true : false;
  895. }
  896. return preg_match("//u", $string) ? true : false;
  897. }
  898. }
  899. // vim: set filetype=php expandtab tabstop=4 shiftwidth=4 autoindent smartindent: