xlsxwriter.class.php 42 KB

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