ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
Worksheet.php
Go to the documentation of this file.
1 <?php
2 
4 
5 use GdImage;
20 
21 // Original file header of PEAR::Spreadsheet_Excel_Writer_Worksheet (used as the base for this class):
22 // -----------------------------------------------------------------------------------------
23 // /*
24 // * Module written/ported by Xavier Noguer <xnoguer@rezebra.com>
25 // *
26 // * The majority of this is _NOT_ my code. I simply ported it from the
27 // * PERL Spreadsheet::WriteExcel module.
28 // *
29 // * The author of the Spreadsheet::WriteExcel module is John McNamara
30 // * <jmcnamara@cpan.org>
31 // *
32 // * I _DO_ maintain this code, and John McNamara has nothing to do with the
33 // * porting of this code to PHP. Any questions directly related to this
34 // * class library should be directed to me.
35 // *
36 // * License Information:
37 // *
38 // * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets
39 // * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com
40 // *
41 // * This library is free software; you can redistribute it and/or
42 // * modify it under the terms of the GNU Lesser General Public
43 // * License as published by the Free Software Foundation; either
44 // * version 2.1 of the License, or (at your option) any later version.
45 // *
46 // * This library is distributed in the hope that it will be useful,
47 // * but WITHOUT ANY WARRANTY; without even the implied warranty of
48 // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
49 // * Lesser General Public License for more details.
50 // *
51 // * You should have received a copy of the GNU Lesser General Public
52 // * License along with this library; if not, write to the Free Software
53 // * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
54 // */
55 class Worksheet extends BIFFwriter
56 {
62  private $parser;
63 
70 
76  private $columnInfo;
77 
83  private $selection;
84 
90  private $activePane;
91 
97  private $outlineOn;
98 
104  private $outlineStyle;
105 
111  private $outlineBelow;
112 
118  private $outlineRight;
119 
125  private $stringTotal;
126 
132  private $stringUnique;
133 
139  private $stringTable;
140 
144  private $colors;
145 
151  private $firstRowIndex;
152 
158  private $lastRowIndex;
159 
166 
173 
179  public $phpSheet;
180 
187 
193  private $escher;
194 
201 
206 
210  private $printHeaders;
211 
223  public function __construct(&$str_total, &$str_unique, &$str_table, &$colors, Parser $parser, $preCalculateFormulas, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet)
224  {
225  // It needs to call its parent's constructor explicitly
226  parent::__construct();
227 
228  $this->preCalculateFormulas = $preCalculateFormulas;
229  $this->stringTotal = &$str_total;
230  $this->stringUnique = &$str_unique;
231  $this->stringTable = &$str_table;
232  $this->colors = &$colors;
233  $this->parser = $parser;
234 
235  $this->phpSheet = $phpSheet;
236 
237  $this->xlsStringMaxLength = 255;
238  $this->columnInfo = [];
239  $this->selection = [0, 0, 0, 0];
240  $this->activePane = 3;
241 
242  $this->printHeaders = 0;
243 
244  $this->outlineStyle = false;
245  $this->outlineBelow = true;
246  $this->outlineRight = true;
247  $this->outlineOn = true;
248 
249  $this->fontHashIndex = [];
250 
251  // calculate values for DIMENSIONS record
252  $minR = 1;
253  $minC = 'A';
254 
255  $maxR = $this->phpSheet->getHighestRow();
256  $maxC = $this->phpSheet->getHighestColumn();
257 
258  // Determine lowest and highest column and row
259  $this->firstRowIndex = $minR;
260  $this->lastRowIndex = ($maxR > 65535) ? 65535 : $maxR;
261 
262  $this->firstColumnIndex = Coordinate::columnIndexFromString($minC);
263  $this->lastColumnIndex = Coordinate::columnIndexFromString($maxC);
264 
265  if ($this->lastColumnIndex > 255) {
266  $this->lastColumnIndex = 255;
267  }
268 
269  $this->countCellStyleXfs = count($phpSheet->getParent()->getCellStyleXfCollection());
270  }
271 
278  public function close(): void
279  {
281 
282  // Storing selected cells and active sheet because it changes while parsing cells with formulas.
283  $selectedCells = $this->phpSheet->getSelectedCells();
284  $activeSheetIndex = $this->phpSheet->getParent()->getActiveSheetIndex();
285 
286  // Write BOF record
287  $this->storeBof(0x0010);
288 
289  // Write PRINTHEADERS
290  $this->writePrintHeaders();
291 
292  // Write PRINTGRIDLINES
293  $this->writePrintGridlines();
294 
295  // Write GRIDSET
296  $this->writeGridset();
297 
298  // Calculate column widths
299  $phpSheet->calculateColumnWidths();
300 
301  // Column dimensions
302  if (($defaultWidth = $phpSheet->getDefaultColumnDimension()->getWidth()) < 0) {
303  $defaultWidth = \PhpOffice\PhpSpreadsheet\Shared\Font::getDefaultColumnWidthByFont($phpSheet->getParent()->getDefaultStyle()->getFont());
304  }
305 
306  $columnDimensions = $phpSheet->getColumnDimensions();
307  $maxCol = $this->lastColumnIndex - 1;
308  for ($i = 0; $i <= $maxCol; ++$i) {
309  $hidden = 0;
310  $level = 0;
311  $xfIndex = 15; // there are 15 cell style Xfs
312 
313  $width = $defaultWidth;
314 
315  $columnLetter = Coordinate::stringFromColumnIndex($i + 1);
316  if (isset($columnDimensions[$columnLetter])) {
317  $columnDimension = $columnDimensions[$columnLetter];
318  if ($columnDimension->getWidth() >= 0) {
319  $width = $columnDimension->getWidth();
320  }
321  $hidden = $columnDimension->getVisible() ? 0 : 1;
322  $level = $columnDimension->getOutlineLevel();
323  $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs
324  }
325 
326  // Components of columnInfo:
327  // $firstcol first column on the range
328  // $lastcol last column on the range
329  // $width width to set
330  // $xfIndex The optional cell style Xf index to apply to the columns
331  // $hidden The optional hidden atribute
332  // $level The optional outline level
333  $this->columnInfo[] = [$i, $i, $width, $xfIndex, $hidden, $level];
334  }
335 
336  // Write GUTS
337  $this->writeGuts();
338 
339  // Write DEFAULTROWHEIGHT
340  $this->writeDefaultRowHeight();
341  // Write WSBOOL
342  $this->writeWsbool();
343  // Write horizontal and vertical page breaks
344  $this->writeBreaks();
345  // Write page header
346  $this->writeHeader();
347  // Write page footer
348  $this->writeFooter();
349  // Write page horizontal centering
350  $this->writeHcenter();
351  // Write page vertical centering
352  $this->writeVcenter();
353  // Write left margin
354  $this->writeMarginLeft();
355  // Write right margin
356  $this->writeMarginRight();
357  // Write top margin
358  $this->writeMarginTop();
359  // Write bottom margin
360  $this->writeMarginBottom();
361  // Write page setup
362  $this->writeSetup();
363  // Write sheet protection
364  $this->writeProtect();
365  // Write SCENPROTECT
366  $this->writeScenProtect();
367  // Write OBJECTPROTECT
368  $this->writeObjectProtect();
369  // Write sheet password
370  $this->writePassword();
371  // Write DEFCOLWIDTH record
372  $this->writeDefcol();
373 
374  // Write the COLINFO records if they exist
375  if (!empty($this->columnInfo)) {
376  $colcount = count($this->columnInfo);
377  for ($i = 0; $i < $colcount; ++$i) {
378  $this->writeColinfo($this->columnInfo[$i]);
379  }
380  }
381  $autoFilterRange = $phpSheet->getAutoFilter()->getRange();
382  if (!empty($autoFilterRange)) {
383  // Write AUTOFILTERINFO
384  $this->writeAutoFilterInfo();
385  }
386 
387  // Write sheet dimensions
388  $this->writeDimensions();
389 
390  // Row dimensions
391  foreach ($phpSheet->getRowDimensions() as $rowDimension) {
392  $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs
393  $this->writeRow(
394  $rowDimension->getRowIndex() - 1,
395  (int) $rowDimension->getRowHeight(),
396  $xfIndex,
397  !$rowDimension->getVisible(),
398  $rowDimension->getOutlineLevel()
399  );
400  }
401 
402  // Write Cells
403  foreach ($phpSheet->getCoordinates() as $coordinate) {
404  $cell = $phpSheet->getCell($coordinate);
405  $row = $cell->getRow() - 1;
406  $column = Coordinate::columnIndexFromString($cell->getColumn()) - 1;
407 
408  // Don't break Excel break the code!
409  if ($row > 65535 || $column > 255) {
410  throw new WriterException('Rows or columns overflow! Excel5 has limit to 65535 rows and 255 columns. Use XLSX instead.');
411  }
412 
413  // Write cell value
414  $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs
415 
416  $cVal = $cell->getValue();
417  if ($cVal instanceof RichText) {
418  $arrcRun = [];
419  $str_pos = 0;
420  $elements = $cVal->getRichTextElements();
421  foreach ($elements as $element) {
422  // FONT Index
423  if ($element instanceof Run) {
424  $str_fontidx = $this->fontHashIndex[$element->getFont()->getHashCode()];
425  } else {
426  $str_fontidx = 0;
427  }
428  $arrcRun[] = ['strlen' => $str_pos, 'fontidx' => $str_fontidx];
429  // Position FROM
430  $str_pos += StringHelper::countCharacters($element->getText(), 'UTF-8');
431  }
432  $this->writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun);
433  } else {
434  switch ($cell->getDatatype()) {
436  case DataType::TYPE_NULL:
437  if ($cVal === '' || $cVal === null) {
438  $this->writeBlank($row, $column, $xfIndex);
439  } else {
440  $this->writeString($row, $column, $cVal, $xfIndex);
441  }
442 
443  break;
445  $this->writeNumber($row, $column, $cVal, $xfIndex);
446 
447  break;
449  $calculatedValue = $this->preCalculateFormulas ?
450  $cell->getCalculatedValue() : null;
451  if (self::WRITE_FORMULA_EXCEPTION == $this->writeFormula($row, $column, $cVal, $xfIndex, $calculatedValue)) {
452  if ($calculatedValue === null) {
453  $calculatedValue = $cell->getCalculatedValue();
454  }
455  $calctype = gettype($calculatedValue);
456  switch ($calctype) {
457  case 'integer':
458  case 'double':
459  $this->writeNumber($row, $column, $calculatedValue, $xfIndex);
460 
461  break;
462  case 'string':
463  $this->writeString($row, $column, $calculatedValue, $xfIndex);
464 
465  break;
466  case 'boolean':
467  $this->writeBoolErr($row, $column, $calculatedValue, 0, $xfIndex);
468 
469  break;
470  default:
471  $this->writeString($row, $column, $cVal, $xfIndex);
472  }
473  }
474 
475  break;
476  case DataType::TYPE_BOOL:
477  $this->writeBoolErr($row, $column, $cVal, 0, $xfIndex);
478 
479  break;
481  $this->writeBoolErr($row, $column, ErrorCode::error($cVal), 1, $xfIndex);
482 
483  break;
484  }
485  }
486  }
487 
488  // Append
489  $this->writeMsoDrawing();
490 
491  // Restoring active sheet.
492  $this->phpSheet->getParent()->setActiveSheetIndex($activeSheetIndex);
493 
494  // Write WINDOW2 record
495  $this->writeWindow2();
496 
497  // Write PLV record
498  $this->writePageLayoutView();
499 
500  // Write ZOOM record
501  $this->writeZoom();
502  if ($phpSheet->getFreezePane()) {
503  $this->writePanes();
504  }
505 
506  // Restoring selected cells.
507  $this->phpSheet->setSelectedCells($selectedCells);
508 
509  // Write SELECTION record
510  $this->writeSelection();
511 
512  // Write MergedCellsTable Record
513  $this->writeMergedCells();
514 
515  // Hyperlinks
516  foreach ($phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) {
517  [$column, $row] = Coordinate::indexesFromString($coordinate);
518 
519  $url = $hyperlink->getUrl();
520 
521  if (strpos($url, 'sheet://') !== false) {
522  // internal to current workbook
523  $url = str_replace('sheet://', 'internal:', $url);
524  } elseif (preg_match('/^(http:|https:|ftp:|mailto:)/', $url)) {
525  // URL
526  } else {
527  // external (local file)
528  $url = 'external:' . $url;
529  }
530 
531  $this->writeUrl($row - 1, $column - 1, $url);
532  }
533 
534  $this->writeDataValidity();
535  $this->writeSheetLayout();
536 
537  // Write SHEETPROTECTION record
538  $this->writeSheetProtection();
539  $this->writeRangeProtection();
540 
541  $arrConditionalStyles = $phpSheet->getConditionalStylesCollection();
542  if (!empty($arrConditionalStyles)) {
543  $arrConditional = [];
544 
545  $cfHeaderWritten = false;
546  // Write ConditionalFormattingTable records
547  foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) {
548  foreach ($conditionalStyles as $conditional) {
550  if (
551  $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION ||
552  $conditional->getConditionType() == Conditional::CONDITION_CELLIS
553  ) {
554  // Write CFHEADER record (only if there are Conditional Styles that we are able to write)
555  if ($cfHeaderWritten === false) {
556  $this->writeCFHeader();
557  $cfHeaderWritten = true;
558  }
559  if (!isset($arrConditional[$conditional->getHashCode()])) {
560  // This hash code has been handled
561  $arrConditional[$conditional->getHashCode()] = true;
562 
563  // Write CFRULE record
564  $this->writeCFRule($conditional);
565  }
566  }
567  }
568  }
569  }
570 
571  $this->storeEof();
572  }
573 
583  private function writeBIFF8CellRangeAddressFixed($range)
584  {
585  $explodes = explode(':', $range);
586 
587  // extract first cell, e.g. 'A1'
588  $firstCell = $explodes[0];
589 
590  // extract last cell, e.g. 'B6'
591  if (count($explodes) == 1) {
592  $lastCell = $firstCell;
593  } else {
594  $lastCell = $explodes[1];
595  }
596 
597  $firstCellCoordinates = Coordinate::indexesFromString($firstCell); // e.g. [0, 1]
598  $lastCellCoordinates = Coordinate::indexesFromString($lastCell); // e.g. [1, 6]
599 
600  return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, $firstCellCoordinates[0] - 1, $lastCellCoordinates[0] - 1);
601  }
602 
609  public function getData()
610  {
611  // Return data stored in memory
612  if (isset($this->_data)) {
613  $tmp = $this->_data;
614  $this->_data = null;
615 
616  return $tmp;
617  }
618 
619  // No data to return
620  return '';
621  }
622 
628  public function printRowColHeaders($print = 1): void
629  {
630  $this->printHeaders = $print;
631  }
632 
642  public function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false): void
643  {
644  $this->outlineOn = $visible;
645  $this->outlineBelow = $symbols_below;
646  $this->outlineRight = $symbols_right;
647  $this->outlineStyle = $auto_style;
648  }
649 
665  private function writeNumber($row, $col, $num, $xfIndex)
666  {
667  $record = 0x0203; // Record identifier
668  $length = 0x000E; // Number of bytes to follow
669 
670  $header = pack('vv', $record, $length);
671  $data = pack('vvv', $row, $col, $xfIndex);
672  $xl_double = pack('d', $num);
673  if (self::getByteOrder()) { // if it's Big Endian
674  $xl_double = strrev($xl_double);
675  }
676 
677  $this->append($header . $data . $xl_double);
678 
679  return 0;
680  }
681 
690  private function writeString($row, $col, $str, $xfIndex): void
691  {
692  $this->writeLabelSst($row, $col, $str, $xfIndex);
693  }
694 
705  private function writeRichTextString($row, $col, $str, $xfIndex, $arrcRun): void
706  {
707  $record = 0x00FD; // Record identifier
708  $length = 0x000A; // Bytes to follow
709  $str = StringHelper::UTF8toBIFF8UnicodeShort($str, $arrcRun);
710 
711  // check if string is already present
712  if (!isset($this->stringTable[$str])) {
713  $this->stringTable[$str] = $this->stringUnique++;
714  }
716 
717  $header = pack('vv', $record, $length);
718  $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]);
719  $this->append($header . $data);
720  }
721 
732  private function writeLabelSst($row, $col, $str, $xfIndex): void
733  {
734  $record = 0x00FD; // Record identifier
735  $length = 0x000A; // Bytes to follow
736 
738 
739  // check if string is already present
740  if (!isset($this->stringTable[$str])) {
741  $this->stringTable[$str] = $this->stringUnique++;
742  }
744 
745  $header = pack('vv', $record, $length);
746  $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]);
747  $this->append($header . $data);
748  }
749 
768  public function writeBlank($row, $col, $xfIndex)
769  {
770  $record = 0x0201; // Record identifier
771  $length = 0x0006; // Number of bytes to follow
772 
773  $header = pack('vv', $record, $length);
774  $data = pack('vvv', $row, $col, $xfIndex);
775  $this->append($header . $data);
776 
777  return 0;
778  }
779 
791  private function writeBoolErr($row, $col, $value, $isError, $xfIndex)
792  {
793  $record = 0x0205;
794  $length = 8;
795 
796  $header = pack('vv', $record, $length);
797  $data = pack('vvvCC', $row, $col, $xfIndex, $value, $isError);
798  $this->append($header . $data);
799 
800  return 0;
801  }
802 
807 
826  private function writeFormula($row, $col, $formula, $xfIndex, $calculatedValue)
827  {
828  $record = 0x0006; // Record identifier
829  // Initialize possible additional value for STRING record that should be written after the FORMULA record?
830  $stringValue = null;
831 
832  // calculated value
833  if (isset($calculatedValue)) {
834  // Since we can't yet get the data type of the calculated value,
835  // we use best effort to determine data type
836  if (is_bool($calculatedValue)) {
837  // Boolean value
838  $num = pack('CCCvCv', 0x01, 0x00, (int) $calculatedValue, 0x00, 0x00, 0xFFFF);
839  } elseif (is_int($calculatedValue) || is_float($calculatedValue)) {
840  // Numeric value
841  $num = pack('d', $calculatedValue);
842  } elseif (is_string($calculatedValue)) {
843  $errorCodes = DataType::getErrorCodes();
844  if (isset($errorCodes[$calculatedValue])) {
845  // Error value
846  $num = pack('CCCvCv', 0x02, 0x00, ErrorCode::error($calculatedValue), 0x00, 0x00, 0xFFFF);
847  } elseif ($calculatedValue === '') {
848  // Empty string (and BIFF8)
849  $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
850  } else {
851  // Non-empty string value (or empty string BIFF5)
852  $stringValue = $calculatedValue;
853  $num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF);
854  }
855  } else {
856  // We are really not supposed to reach here
857  $num = pack('d', 0x00);
858  }
859  } else {
860  $num = pack('d', 0x00);
861  }
862 
863  $grbit = 0x03; // Option flags
864  $unknown = 0x0000; // Must be zero
865 
866  // Strip the '=' or '@' sign at the beginning of the formula string
867  if ($formula[0] == '=') {
868  $formula = substr($formula, 1);
869  } else {
870  // Error handling
871  $this->writeString($row, $col, 'Unrecognised character for formula', 0);
872 
873  return self::WRITE_FORMULA_ERRORS;
874  }
875 
876  // Parse the formula using the parser in Parser.php
877  try {
878  $this->parser->parse($formula);
879  $formula = $this->parser->toReversePolish();
880 
881  $formlen = strlen($formula); // Length of the binary string
882  $length = 0x16 + $formlen; // Length of the record data
883 
884  $header = pack('vv', $record, $length);
885 
886  $data = pack('vvv', $row, $col, $xfIndex)
887  . $num
888  . pack('vVv', $grbit, $unknown, $formlen);
889  $this->append($header . $data . $formula);
890 
891  // Append also a STRING record if necessary
892  if ($stringValue !== null) {
893  $this->writeStringRecord($stringValue);
894  }
895 
896  return self::WRITE_FORMULA_NORMAL;
897  } catch (PhpSpreadsheetException $e) {
898  return self::WRITE_FORMULA_EXCEPTION;
899  }
900  }
901 
907  private function writeStringRecord($stringValue): void
908  {
909  $record = 0x0207; // Record identifier
911 
912  $length = strlen($data);
913  $header = pack('vv', $record, $length);
914 
915  $this->append($header . $data);
916  }
917 
933  private function writeUrl($row, $col, $url): void
934  {
935  // Add start row and col to arg list
936  $this->writeUrlRange($row, $col, $row, $col, $url);
937  }
938 
953  private function writeUrlRange($row1, $col1, $row2, $col2, $url): void
954  {
955  // Check for internal/external sheet links or default to web link
956  if (preg_match('[^internal:]', $url)) {
957  $this->writeUrlInternal($row1, $col1, $row2, $col2, $url);
958  }
959  if (preg_match('[^external:]', $url)) {
960  $this->writeUrlExternal($row1, $col1, $row2, $col2, $url);
961  }
962 
963  $this->writeUrlWeb($row1, $col1, $row2, $col2, $url);
964  }
965 
979  public function writeUrlWeb($row1, $col1, $row2, $col2, $url): void
980  {
981  $record = 0x01B8; // Record identifier
982 
983  // Pack the undocumented parts of the hyperlink stream
984  $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000');
985  $unknown2 = pack('H*', 'E0C9EA79F9BACE118C8200AA004BA90B');
986 
987  // Pack the option flags
988  $options = pack('V', 0x03);
989 
990  // Convert URL to a null terminated wchar string
991  $url = implode("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY));
992  $url = $url . "\0\0\0";
993 
994  // Pack the length of the URL
995  $url_len = pack('V', strlen($url));
996 
997  // Calculate the data length
998  $length = 0x34 + strlen($url);
999 
1000  // Pack the header data
1001  $header = pack('vv', $record, $length);
1002  $data = pack('vvvv', $row1, $row2, $col1, $col2);
1003 
1004  // Write the packed data
1005  $this->append($header . $data . $unknown1 . $options . $unknown2 . $url_len . $url);
1006  }
1007 
1019  private function writeUrlInternal($row1, $col1, $row2, $col2, $url): void
1020  {
1021  $record = 0x01B8; // Record identifier
1022 
1023  // Strip URL type
1024  $url = preg_replace('/^internal:/', '', $url);
1025 
1026  // Pack the undocumented parts of the hyperlink stream
1027  $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000');
1028 
1029  // Pack the option flags
1030  $options = pack('V', 0x08);
1031 
1032  // Convert the URL type and to a null terminated wchar string
1033  $url .= "\0";
1034 
1035  // character count
1036  $url_len = StringHelper::countCharacters($url);
1037  $url_len = pack('V', $url_len);
1038 
1039  $url = StringHelper::convertEncoding($url, 'UTF-16LE', 'UTF-8');
1040 
1041  // Calculate the data length
1042  $length = 0x24 + strlen($url);
1043 
1044  // Pack the header data
1045  $header = pack('vv', $record, $length);
1046  $data = pack('vvvv', $row1, $row2, $col1, $col2);
1047 
1048  // Write the packed data
1049  $this->append($header . $data . $unknown1 . $options . $url_len . $url);
1050  }
1051 
1067  private function writeUrlExternal($row1, $col1, $row2, $col2, $url): void
1068  {
1069  // Network drives are different. We will handle them separately
1070  // MS/Novell network drives and shares start with \\
1071  if (preg_match('[^external:\\\\]', $url)) {
1072  return;
1073  }
1074 
1075  $record = 0x01B8; // Record identifier
1076  $length = 0x00000; // Bytes to follow
1077 
1078  // Strip URL type and change Unix dir separator to Dos style (if needed)
1079  //
1080  $url = preg_replace('/^external:/', '', $url);
1081  $url = preg_replace('/\//', '\\', $url);
1082 
1083  // Determine if the link is relative or absolute:
1084  // relative if link contains no dir separator, "somefile.xls"
1085  // relative if link starts with up-dir, "..\..\somefile.xls"
1086  // otherwise, absolute
1087 
1088  $absolute = 0x00; // relative path
1089  if (preg_match('/^[A-Z]:/', $url)) {
1090  $absolute = 0x02; // absolute path on Windows, e.g. C:\...
1091  }
1093 
1094  // Determine if the link contains a sheet reference and change some of the
1095  // parameters accordingly.
1096  // Split the dir name and sheet name (if it exists)
1098  if (preg_match('/\\#/', $url)) {
1099  $link_type |= 0x08;
1100  }
1101 
1102  // Pack the link type
1103  $link_type = pack('V', $link_type);
1104 
1105  // Calculate the up-level dir count e.g.. (..\..\..\ == 3)
1106  $up_count = preg_match_all('/\\.\\.\\\\/', $dir_long, $useless);
1107  $up_count = pack('v', $up_count);
1108 
1109  // Store the short dos dir name (null terminated)
1110  $dir_short = preg_replace('/\\.\\.\\\\/', '', $dir_long) . "\0";
1111 
1112  // Store the long dir name as a wchar string (non-null terminated)
1113  $dir_long = $dir_long . "\0";
1114 
1115  // Pack the lengths of the dir strings
1116  $dir_short_len = pack('V', strlen($dir_short));
1117  $dir_long_len = pack('V', strlen($dir_long));
1118  $stream_len = pack('V', 0); //strlen($dir_long) + 0x06);
1119 
1120  // Pack the undocumented parts of the hyperlink stream
1121  $unknown1 = pack('H*', 'D0C9EA79F9BACE118C8200AA004BA90B02000000');
1122  $unknown2 = pack('H*', '0303000000000000C000000000000046');
1123  $unknown3 = pack('H*', 'FFFFADDE000000000000000000000000000000000000000');
1124  $unknown4 = pack('v', 0x03);
1125 
1126  // Pack the main data stream
1127  $data = pack('vvvv', $row1, $row2, $col1, $col2) .
1128  $unknown1 .
1129  $link_type .
1130  $unknown2 .
1131  $up_count .
1132  $dir_short_len .
1133  $dir_short .
1134  $unknown3 .
1135  $stream_len; /*.
1136  $dir_long_len .
1137  $unknown4 .
1138  $dir_long .
1139  $sheet_len .
1140  $sheet ;*/
1141 
1142  // Pack the header data
1143  $length = strlen($data);
1144  $header = pack('vv', $record, $length);
1145 
1146  // Write the packed data
1147  $this->append($header . $data);
1148  }
1149 
1160  private function writeRow($row, $height, $xfIndex, $hidden = false, $level = 0): void
1161  {
1162  $record = 0x0208; // Record identifier
1163  $length = 0x0010; // Number of bytes to follow
1164 
1165  $colMic = 0x0000; // First defined column
1166  $colMac = 0x0000; // Last defined column
1167  $irwMac = 0x0000; // Used by Excel to optimise loading
1168  $reserved = 0x0000; // Reserved
1169  $grbit = 0x0000; // Option flags
1170  $ixfe = $xfIndex;
1171 
1172  if ($height < 0) {
1173  $height = null;
1174  }
1175 
1176  // Use writeRow($row, null, $XF) to set XF format without setting height
1177  if ($height !== null) {
1178  $miyRw = $height * 20; // row height
1179  } else {
1180  $miyRw = 0xff; // default row height is 256
1181  }
1182 
1183  // Set the options flags. fUnsynced is used to show that the font and row
1184  // heights are not compatible. This is usually the case for WriteExcel.
1185  // The collapsed flag 0x10 doesn't seem to be used to indicate that a row
1186  // is collapsed. Instead it is used to indicate that the previous row is
1187  // collapsed. The zero height flag, 0x20, is used to collapse a row.
1188 
1189  $grbit |= $level;
1190  if ($hidden === true) {
1191  $grbit |= 0x0030;
1192  }
1193  if ($height !== null) {
1194  $grbit |= 0x0040; // fUnsynced
1195  }
1196  if ($xfIndex !== 0xF) {
1197  $grbit |= 0x0080;
1198  }
1199  $grbit |= 0x0100;
1200 
1201  $header = pack('vv', $record, $length);
1202  $data = pack('vvvvvvvv', $row, $colMic, $colMac, $miyRw, $irwMac, $reserved, $grbit, $ixfe);
1203  $this->append($header . $data);
1204  }
1205 
1209  private function writeDimensions(): void
1210  {
1211  $record = 0x0200; // Record identifier
1212 
1213  $length = 0x000E;
1214  $data = pack('VVvvv', $this->firstRowIndex, $this->lastRowIndex + 1, $this->firstColumnIndex, $this->lastColumnIndex + 1, 0x0000); // reserved
1215 
1216  $header = pack('vv', $record, $length);
1217  $this->append($header . $data);
1218  }
1219 
1223  private function writeWindow2(): void
1224  {
1225  $record = 0x023E; // Record identifier
1226  $length = 0x0012;
1227 
1228  $grbit = 0x00B6; // Option flags
1229  $rwTop = 0x0000; // Top row visible in window
1230  $colLeft = 0x0000; // Leftmost column visible in window
1231 
1232  // The options flags that comprise $grbit
1233  $fDspFmla = 0; // 0 - bit
1234  $fDspGrid = $this->phpSheet->getShowGridlines() ? 1 : 0; // 1
1235  $fDspRwCol = $this->phpSheet->getShowRowColHeaders() ? 1 : 0; // 2
1236  $fFrozen = $this->phpSheet->getFreezePane() ? 1 : 0; // 3
1237  $fDspZeros = 1; // 4
1238  $fDefaultHdr = 1; // 5
1239  $fArabic = $this->phpSheet->getRightToLeft() ? 1 : 0; // 6
1240  $fDspGuts = $this->outlineOn; // 7
1241  $fFrozenNoSplit = 0; // 0 - bit
1242  // no support in PhpSpreadsheet for selected sheet, therefore sheet is only selected if it is the active sheet
1243  $fSelected = ($this->phpSheet === $this->phpSheet->getParent()->getActiveSheet()) ? 1 : 0;
1244  $fPageBreakPreview = $this->phpSheet->getSheetView()->getView() === SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW;
1245 
1246  $grbit = $fDspFmla;
1247  $grbit |= $fDspGrid << 1;
1248  $grbit |= $fDspRwCol << 2;
1249  $grbit |= $fFrozen << 3;
1250  $grbit |= $fDspZeros << 4;
1251  $grbit |= $fDefaultHdr << 5;
1252  $grbit |= $fArabic << 6;
1253  $grbit |= $fDspGuts << 7;
1254  $grbit |= $fFrozenNoSplit << 8;
1255  $grbit |= $fSelected << 9; // Selected sheets.
1256  $grbit |= $fSelected << 10; // Active sheet.
1257  $grbit |= $fPageBreakPreview << 11;
1258 
1259  $header = pack('vv', $record, $length);
1260  $data = pack('vvv', $grbit, $rwTop, $colLeft);
1261 
1262  // FIXME !!!
1263  $rgbHdr = 0x0040; // Row/column heading and gridline color index
1264  $zoom_factor_page_break = ($fPageBreakPreview ? $this->phpSheet->getSheetView()->getZoomScale() : 0x0000);
1265  $zoom_factor_normal = $this->phpSheet->getSheetView()->getZoomScaleNormal();
1266 
1267  $data .= pack('vvvvV', $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000);
1268 
1269  $this->append($header . $data);
1270  }
1271 
1275  private function writeDefaultRowHeight(): void
1276  {
1277  $defaultRowHeight = $this->phpSheet->getDefaultRowDimension()->getRowHeight();
1278 
1279  if ($defaultRowHeight < 0) {
1280  return;
1281  }
1282 
1283  // convert to twips
1284  $defaultRowHeight = (int) 20 * $defaultRowHeight;
1285 
1286  $record = 0x0225; // Record identifier
1287  $length = 0x0004; // Number of bytes to follow
1288 
1289  $header = pack('vv', $record, $length);
1290  $data = pack('vv', 1, $defaultRowHeight);
1291  $this->append($header . $data);
1292  }
1293 
1297  private function writeDefcol(): void
1298  {
1299  $defaultColWidth = 8;
1300 
1301  $record = 0x0055; // Record identifier
1302  $length = 0x0002; // Number of bytes to follow
1303 
1304  $header = pack('vv', $record, $length);
1305  $data = pack('v', $defaultColWidth);
1306  $this->append($header . $data);
1307  }
1308 
1323  private function writeColinfo($col_array): void
1324  {
1325  $colFirst = $col_array[0] ?? null;
1326  $colLast = $col_array[1] ?? null;
1327  $coldx = $col_array[2] ?? 8.43;
1328  $xfIndex = $col_array[3] ?? 15;
1329  $grbit = $col_array[4] ?? 0;
1330  $level = $col_array[5] ?? 0;
1331 
1332  $record = 0x007D; // Record identifier
1333  $length = 0x000C; // Number of bytes to follow
1334 
1335  $coldx *= 256; // Convert to units of 1/256 of a char
1336 
1337  $ixfe = $xfIndex;
1338  $reserved = 0x0000; // Reserved
1339 
1340  $level = max(0, min($level, 7));
1341  $grbit |= $level << 8;
1342 
1343  $header = pack('vv', $record, $length);
1344  $data = pack('vvvvvv', $colFirst, $colLast, $coldx, $ixfe, $grbit, $reserved);
1345  $this->append($header . $data);
1346  }
1347 
1351  private function writeSelection(): void
1352  {
1353  // look up the selected cell range
1354  $selectedCells = Coordinate::splitRange($this->phpSheet->getSelectedCells());
1355  $selectedCells = $selectedCells[0];
1356  if (count($selectedCells) == 2) {
1357  [$first, $last] = $selectedCells;
1358  } else {
1359  $first = $selectedCells[0];
1360  $last = $selectedCells[0];
1361  }
1362 
1363  [$colFirst, $rwFirst] = Coordinate::coordinateFromString($first);
1364  $colFirst = Coordinate::columnIndexFromString($colFirst) - 1; // base 0 column index
1365  --$rwFirst; // base 0 row index
1366 
1367  [$colLast, $rwLast] = Coordinate::coordinateFromString($last);
1368  $colLast = Coordinate::columnIndexFromString($colLast) - 1; // base 0 column index
1369  --$rwLast; // base 0 row index
1370 
1371  // make sure we are not out of bounds
1372  $colFirst = min($colFirst, 255);
1373  $colLast = min($colLast, 255);
1374 
1375  $rwFirst = min($rwFirst, 65535);
1376  $rwLast = min($rwLast, 65535);
1377 
1378  $record = 0x001D; // Record identifier
1379  $length = 0x000F; // Number of bytes to follow
1380 
1381  $pnn = $this->activePane; // Pane position
1382  $rwAct = $rwFirst; // Active row
1383  $colAct = $colFirst; // Active column
1384  $irefAct = 0; // Active cell ref
1385  $cref = 1; // Number of refs
1386 
1387  // Swap last row/col for first row/col as necessary
1388  if ($rwFirst > $rwLast) {
1389  [$rwFirst, $rwLast] = [$rwLast, $rwFirst];
1390  }
1391 
1392  if ($colFirst > $colLast) {
1393  [$colFirst, $colLast] = [$colLast, $colFirst];
1394  }
1395 
1396  $header = pack('vv', $record, $length);
1397  $data = pack('CvvvvvvCC', $pnn, $rwAct, $colAct, $irefAct, $cref, $rwFirst, $rwLast, $colFirst, $colLast);
1398  $this->append($header . $data);
1399  }
1400 
1404  private function writeMergedCells(): void
1405  {
1406  $mergeCells = $this->phpSheet->getMergeCells();
1407  $countMergeCells = count($mergeCells);
1408 
1409  if ($countMergeCells == 0) {
1410  return;
1411  }
1412 
1413  // maximum allowed number of merged cells per record
1414  $maxCountMergeCellsPerRecord = 1027;
1415 
1416  // record identifier
1417  $record = 0x00E5;
1418 
1419  // counter for total number of merged cells treated so far by the writer
1420  $i = 0;
1421 
1422  // counter for number of merged cells written in record currently being written
1423  $j = 0;
1424 
1425  // initialize record data
1426  $recordData = '';
1427 
1428  // loop through the merged cells
1429  foreach ($mergeCells as $mergeCell) {
1430  ++$i;
1431  ++$j;
1432 
1433  // extract the row and column indexes
1434  $range = Coordinate::splitRange($mergeCell);
1435  [$first, $last] = $range[0];
1436  [$firstColumn, $firstRow] = Coordinate::indexesFromString($first);
1437  [$lastColumn, $lastRow] = Coordinate::indexesFromString($last);
1438 
1439  $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, $firstColumn - 1, $lastColumn - 1);
1440 
1441  // flush record if we have reached limit for number of merged cells, or reached final merged cell
1442  if ($j == $maxCountMergeCellsPerRecord || $i == $countMergeCells) {
1443  $recordData = pack('v', $j) . $recordData;
1444  $length = strlen($recordData);
1445  $header = pack('vv', $record, $length);
1446  $this->append($header . $recordData);
1447 
1448  // initialize for next record, if any
1449  $recordData = '';
1450  $j = 0;
1451  }
1452  }
1453  }
1454 
1458  private function writeSheetLayout(): void
1459  {
1460  if (!$this->phpSheet->isTabColorSet()) {
1461  return;
1462  }
1463 
1464  $recordData = pack(
1465  'vvVVVvv',
1466  0x0862,
1467  0x0000, // unused
1468  0x00000000, // unused
1469  0x00000000, // unused
1470  0x00000014, // size of record data
1471  $this->colors[$this->phpSheet->getTabColor()->getRGB()], // color index
1472  0x0000 // unused
1473  );
1474 
1475  $length = strlen($recordData);
1476 
1477  $record = 0x0862; // Record identifier
1478  $header = pack('vv', $record, $length);
1479  $this->append($header . $recordData);
1480  }
1481 
1485  private function writeSheetProtection(): void
1486  {
1487  // record identifier
1488  $record = 0x0867;
1489 
1490  // prepare options
1491  $options = (int) !$this->phpSheet->getProtection()->getObjects()
1492  | (int) !$this->phpSheet->getProtection()->getScenarios() << 1
1493  | (int) !$this->phpSheet->getProtection()->getFormatCells() << 2
1494  | (int) !$this->phpSheet->getProtection()->getFormatColumns() << 3
1495  | (int) !$this->phpSheet->getProtection()->getFormatRows() << 4
1496  | (int) !$this->phpSheet->getProtection()->getInsertColumns() << 5
1497  | (int) !$this->phpSheet->getProtection()->getInsertRows() << 6
1498  | (int) !$this->phpSheet->getProtection()->getInsertHyperlinks() << 7
1499  | (int) !$this->phpSheet->getProtection()->getDeleteColumns() << 8
1500  | (int) !$this->phpSheet->getProtection()->getDeleteRows() << 9
1501  | (int) !$this->phpSheet->getProtection()->getSelectLockedCells() << 10
1502  | (int) !$this->phpSheet->getProtection()->getSort() << 11
1503  | (int) !$this->phpSheet->getProtection()->getAutoFilter() << 12
1504  | (int) !$this->phpSheet->getProtection()->getPivotTables() << 13
1505  | (int) !$this->phpSheet->getProtection()->getSelectUnlockedCells() << 14;
1506 
1507  // record data
1508  $recordData = pack(
1509  'vVVCVVvv',
1510  0x0867, // repeated record identifier
1511  0x0000, // not used
1512  0x0000, // not used
1513  0x00, // not used
1514  0x01000200, // unknown data
1515  0xFFFFFFFF, // unknown data
1516  $options, // options
1517  0x0000 // not used
1518  );
1519 
1520  $length = strlen($recordData);
1521  $header = pack('vv', $record, $length);
1522 
1523  $this->append($header . $recordData);
1524  }
1525 
1532  private function writeRangeProtection(): void
1533  {
1534  foreach ($this->phpSheet->getProtectedCells() as $range => $password) {
1535  // number of ranges, e.g. 'A1:B3 C20:D25'
1536  $cellRanges = explode(' ', $range);
1537  $cref = count($cellRanges);
1538 
1539  $recordData = pack(
1540  'vvVVvCVvVv',
1541  0x0868,
1542  0x00,
1543  0x0000,
1544  0x0000,
1545  0x02,
1546  0x0,
1547  0x0000,
1548  $cref,
1549  0x0000,
1550  0x00
1551  );
1552 
1553  foreach ($cellRanges as $cellRange) {
1554  $recordData .= $this->writeBIFF8CellRangeAddressFixed($cellRange);
1555  }
1556 
1557  // the rgbFeat structure
1558  $recordData .= pack(
1559  'VV',
1560  0x0000,
1561  hexdec($password)
1562  );
1563 
1564  $recordData .= StringHelper::UTF8toBIFF8UnicodeLong('p' . md5($recordData));
1565 
1566  $length = strlen($recordData);
1567 
1568  $record = 0x0868; // Record identifier
1569  $header = pack('vv', $record, $length);
1570  $this->append($header . $recordData);
1571  }
1572  }
1573 
1580  private function writePanes(): void
1581  {
1582  if (!$this->phpSheet->getFreezePane()) {
1583  // thaw panes
1584  return;
1585  }
1586 
1587  [$column, $row] = Coordinate::indexesFromString($this->phpSheet->getFreezePane());
1588  $x = $column - 1;
1589  $y = $row - 1;
1590 
1591  [$leftMostColumn, $topRow] = Coordinate::indexesFromString($this->phpSheet->getTopLeftCell());
1592  //Coordinates are zero-based in xls files
1593  $rwTop = $topRow - 1;
1594  $colLeft = $leftMostColumn - 1;
1595 
1596  $record = 0x0041; // Record identifier
1597  $length = 0x000A; // Number of bytes to follow
1598 
1599  // Determine which pane should be active. There is also the undocumented
1600  // option to override this should it be necessary: may be removed later.
1601  $pnnAct = null;
1602  if ($x != 0 && $y != 0) {
1603  $pnnAct = 0; // Bottom right
1604  }
1605  if ($x != 0 && $y == 0) {
1606  $pnnAct = 1; // Top right
1607  }
1608  if ($x == 0 && $y != 0) {
1609  $pnnAct = 2; // Bottom left
1610  }
1611  if ($x == 0 && $y == 0) {
1612  $pnnAct = 3; // Top left
1613  }
1614 
1615  $this->activePane = $pnnAct; // Used in writeSelection
1616 
1617  $header = pack('vv', $record, $length);
1618  $data = pack('vvvvv', $x, $y, $rwTop, $colLeft, $pnnAct);
1619  $this->append($header . $data);
1620  }
1621 
1625  private function writeSetup(): void
1626  {
1627  $record = 0x00A1; // Record identifier
1628  $length = 0x0022; // Number of bytes to follow
1629 
1630  $iPaperSize = $this->phpSheet->getPageSetup()->getPaperSize(); // Paper size
1631  $iScale = $this->phpSheet->getPageSetup()->getScale() ?: 100; // Print scaling factor
1632 
1633  $iPageStart = 0x01; // Starting page number
1634  $iFitWidth = (int) $this->phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide
1635  $iFitHeight = (int) $this->phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high
1636  $grbit = 0x00; // Option flags
1637  $iRes = 0x0258; // Print resolution
1638  $iVRes = 0x0258; // Vertical print resolution
1639 
1640  $numHdr = $this->phpSheet->getPageMargins()->getHeader(); // Header Margin
1641 
1642  $numFtr = $this->phpSheet->getPageMargins()->getFooter(); // Footer Margin
1643  $iCopies = 0x01; // Number of copies
1644 
1645  // Order of printing pages
1646  $fLeftToRight = $this->phpSheet->getPageSetup()->getPageOrder() === PageSetup::PAGEORDER_DOWN_THEN_OVER
1647  ? 0x1 : 0x0;
1648  // Page orientation
1649  $fLandscape = ($this->phpSheet->getPageSetup()->getOrientation() == PageSetup::ORIENTATION_LANDSCAPE)
1650  ? 0x0 : 0x1;
1651 
1652  $fNoPls = 0x0; // Setup not read from printer
1653  $fNoColor = 0x0; // Print black and white
1654  $fDraft = 0x0; // Print draft quality
1655  $fNotes = 0x0; // Print notes
1656  $fNoOrient = 0x0; // Orientation not set
1657  $fUsePage = 0x0; // Use custom starting page
1658 
1659  $grbit = $fLeftToRight;
1660  $grbit |= $fLandscape << 1;
1661  $grbit |= $fNoPls << 2;
1662  $grbit |= $fNoColor << 3;
1663  $grbit |= $fDraft << 4;
1664  $grbit |= $fNotes << 5;
1665  $grbit |= $fNoOrient << 6;
1666  $grbit |= $fUsePage << 7;
1667 
1668  $numHdr = pack('d', $numHdr);
1669  $numFtr = pack('d', $numFtr);
1670  if (self::getByteOrder()) { // if it's Big Endian
1671  $numHdr = strrev($numHdr);
1672  $numFtr = strrev($numFtr);
1673  }
1674 
1675  $header = pack('vv', $record, $length);
1676  $data1 = pack('vvvvvvvv', $iPaperSize, $iScale, $iPageStart, $iFitWidth, $iFitHeight, $grbit, $iRes, $iVRes);
1677  $data2 = $numHdr . $numFtr;
1678  $data3 = pack('v', $iCopies);
1679  $this->append($header . $data1 . $data2 . $data3);
1680  }
1681 
1685  private function writeHeader(): void
1686  {
1687  $record = 0x0014; // Record identifier
1688 
1689  /* removing for now
1690  // need to fix character count (multibyte!)
1691  if (strlen($this->phpSheet->getHeaderFooter()->getOddHeader()) <= 255) {
1692  $str = $this->phpSheet->getHeaderFooter()->getOddHeader(); // header string
1693  } else {
1694  $str = '';
1695  }
1696  */
1697 
1698  $recordData = StringHelper::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddHeader());
1699  $length = strlen($recordData);
1700 
1701  $header = pack('vv', $record, $length);
1702 
1703  $this->append($header . $recordData);
1704  }
1705 
1709  private function writeFooter(): void
1710  {
1711  $record = 0x0015; // Record identifier
1712 
1713  /* removing for now
1714  // need to fix character count (multibyte!)
1715  if (strlen($this->phpSheet->getHeaderFooter()->getOddFooter()) <= 255) {
1716  $str = $this->phpSheet->getHeaderFooter()->getOddFooter();
1717  } else {
1718  $str = '';
1719  }
1720  */
1721 
1722  $recordData = StringHelper::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddFooter());
1723  $length = strlen($recordData);
1724 
1725  $header = pack('vv', $record, $length);
1726 
1727  $this->append($header . $recordData);
1728  }
1729 
1733  private function writeHcenter(): void
1734  {
1735  $record = 0x0083; // Record identifier
1736  $length = 0x0002; // Bytes to follow
1737 
1738  $fHCenter = $this->phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering
1739 
1740  $header = pack('vv', $record, $length);
1741  $data = pack('v', $fHCenter);
1742 
1743  $this->append($header . $data);
1744  }
1745 
1749  private function writeVcenter(): void
1750  {
1751  $record = 0x0084; // Record identifier
1752  $length = 0x0002; // Bytes to follow
1753 
1754  $fVCenter = $this->phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering
1755 
1756  $header = pack('vv', $record, $length);
1757  $data = pack('v', $fVCenter);
1758  $this->append($header . $data);
1759  }
1760 
1764  private function writeMarginLeft(): void
1765  {
1766  $record = 0x0026; // Record identifier
1767  $length = 0x0008; // Bytes to follow
1768 
1769  $margin = $this->phpSheet->getPageMargins()->getLeft(); // Margin in inches
1770 
1771  $header = pack('vv', $record, $length);
1772  $data = pack('d', $margin);
1773  if (self::getByteOrder()) { // if it's Big Endian
1774  $data = strrev($data);
1775  }
1776 
1777  $this->append($header . $data);
1778  }
1779 
1783  private function writeMarginRight(): void
1784  {
1785  $record = 0x0027; // Record identifier
1786  $length = 0x0008; // Bytes to follow
1787 
1788  $margin = $this->phpSheet->getPageMargins()->getRight(); // Margin in inches
1789 
1790  $header = pack('vv', $record, $length);
1791  $data = pack('d', $margin);
1792  if (self::getByteOrder()) { // if it's Big Endian
1793  $data = strrev($data);
1794  }
1795 
1796  $this->append($header . $data);
1797  }
1798 
1802  private function writeMarginTop(): void
1803  {
1804  $record = 0x0028; // Record identifier
1805  $length = 0x0008; // Bytes to follow
1806 
1807  $margin = $this->phpSheet->getPageMargins()->getTop(); // Margin in inches
1808 
1809  $header = pack('vv', $record, $length);
1810  $data = pack('d', $margin);
1811  if (self::getByteOrder()) { // if it's Big Endian
1812  $data = strrev($data);
1813  }
1814 
1815  $this->append($header . $data);
1816  }
1817 
1821  private function writeMarginBottom(): void
1822  {
1823  $record = 0x0029; // Record identifier
1824  $length = 0x0008; // Bytes to follow
1825 
1826  $margin = $this->phpSheet->getPageMargins()->getBottom(); // Margin in inches
1827 
1828  $header = pack('vv', $record, $length);
1829  $data = pack('d', $margin);
1830  if (self::getByteOrder()) { // if it's Big Endian
1831  $data = strrev($data);
1832  }
1833 
1834  $this->append($header . $data);
1835  }
1836 
1840  private function writePrintHeaders(): void
1841  {
1842  $record = 0x002a; // Record identifier
1843  $length = 0x0002; // Bytes to follow
1844 
1845  $fPrintRwCol = $this->printHeaders; // Boolean flag
1846 
1847  $header = pack('vv', $record, $length);
1848  $data = pack('v', $fPrintRwCol);
1849  $this->append($header . $data);
1850  }
1851 
1856  private function writePrintGridlines(): void
1857  {
1858  $record = 0x002b; // Record identifier
1859  $length = 0x0002; // Bytes to follow
1860 
1861  $fPrintGrid = $this->phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag
1862 
1863  $header = pack('vv', $record, $length);
1864  $data = pack('v', $fPrintGrid);
1865  $this->append($header . $data);
1866  }
1867 
1872  private function writeGridset(): void
1873  {
1874  $record = 0x0082; // Record identifier
1875  $length = 0x0002; // Bytes to follow
1876 
1877  $fGridSet = !$this->phpSheet->getPrintGridlines(); // Boolean flag
1878 
1879  $header = pack('vv', $record, $length);
1880  $data = pack('v', $fGridSet);
1881  $this->append($header . $data);
1882  }
1883 
1887  private function writeAutoFilterInfo(): void
1888  {
1889  $record = 0x009D; // Record identifier
1890  $length = 0x0002; // Bytes to follow
1891 
1892  $rangeBounds = Coordinate::rangeBoundaries($this->phpSheet->getAutoFilter()->getRange());
1893  $iNumFilters = 1 + $rangeBounds[1][0] - $rangeBounds[0][0];
1894 
1895  $header = pack('vv', $record, $length);
1896  $data = pack('v', $iNumFilters);
1897  $this->append($header . $data);
1898  }
1899 
1907  private function writeGuts(): void
1908  {
1909  $record = 0x0080; // Record identifier
1910  $length = 0x0008; // Bytes to follow
1911 
1912  $dxRwGut = 0x0000; // Size of row gutter
1913  $dxColGut = 0x0000; // Size of col gutter
1914 
1915  // determine maximum row outline level
1916  $maxRowOutlineLevel = 0;
1917  foreach ($this->phpSheet->getRowDimensions() as $rowDimension) {
1918  $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel());
1919  }
1920 
1921  $col_level = 0;
1922 
1923  // Calculate the maximum column outline level. The equivalent calculation
1924  // for the row outline level is carried out in writeRow().
1925  $colcount = count($this->columnInfo);
1926  for ($i = 0; $i < $colcount; ++$i) {
1927  $col_level = max($this->columnInfo[$i][5], $col_level);
1928  }
1929 
1930  // Set the limits for the outline levels (0 <= x <= 7).
1931  $col_level = max(0, min($col_level, 7));
1932 
1933  // The displayed level is one greater than the max outline levels
1934  if ($maxRowOutlineLevel) {
1935  ++$maxRowOutlineLevel;
1936  }
1937  if ($col_level) {
1938  ++$col_level;
1939  }
1940 
1941  $header = pack('vv', $record, $length);
1942  $data = pack('vvvv', $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level);
1943 
1944  $this->append($header . $data);
1945  }
1946 
1951  private function writeWsbool(): void
1952  {
1953  $record = 0x0081; // Record identifier
1954  $length = 0x0002; // Bytes to follow
1955  $grbit = 0x0000;
1956 
1957  // The only option that is of interest is the flag for fit to page. So we
1958  // set all the options in one go.
1959  //
1960  // Set the option flags
1961  $grbit |= 0x0001; // Auto page breaks visible
1962  if ($this->outlineStyle) {
1963  $grbit |= 0x0020; // Auto outline styles
1964  }
1965  if ($this->phpSheet->getShowSummaryBelow()) {
1966  $grbit |= 0x0040; // Outline summary below
1967  }
1968  if ($this->phpSheet->getShowSummaryRight()) {
1969  $grbit |= 0x0080; // Outline summary right
1970  }
1971  if ($this->phpSheet->getPageSetup()->getFitToPage()) {
1972  $grbit |= 0x0100; // Page setup fit to page
1973  }
1974  if ($this->outlineOn) {
1975  $grbit |= 0x0400; // Outline symbols displayed
1976  }
1977 
1978  $header = pack('vv', $record, $length);
1979  $data = pack('v', $grbit);
1980  $this->append($header . $data);
1981  }
1982 
1986  private function writeBreaks(): void
1987  {
1988  // initialize
1989  $vbreaks = [];
1990  $hbreaks = [];
1991 
1992  foreach ($this->phpSheet->getBreaks() as $cell => $breakType) {
1993  // Fetch coordinates
1994  $coordinates = Coordinate::coordinateFromString($cell);
1995 
1996  // Decide what to do by the type of break
1997  switch ($breakType) {
1998  case \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_COLUMN:
1999  // Add to list of vertical breaks
2000  $vbreaks[] = Coordinate::columnIndexFromString($coordinates[0]) - 1;
2001 
2002  break;
2003  case \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW:
2004  // Add to list of horizontal breaks
2005  $hbreaks[] = $coordinates[1];
2006 
2007  break;
2008  case \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_NONE:
2009  default:
2010  // Nothing to do
2011  break;
2012  }
2013  }
2014 
2015  //horizontal page breaks
2016  if (!empty($hbreaks)) {
2017  // Sort and filter array of page breaks
2018  sort($hbreaks, SORT_NUMERIC);
2019  if ($hbreaks[0] == 0) { // don't use first break if it's 0
2020  array_shift($hbreaks);
2021  }
2022 
2023  $record = 0x001b; // Record identifier
2024  $cbrk = count($hbreaks); // Number of page breaks
2025  $length = 2 + 6 * $cbrk; // Bytes to follow
2026 
2027  $header = pack('vv', $record, $length);
2028  $data = pack('v', $cbrk);
2029 
2030  // Append each page break
2031  foreach ($hbreaks as $hbreak) {
2032  $data .= pack('vvv', $hbreak, 0x0000, 0x00ff);
2033  }
2034 
2035  $this->append($header . $data);
2036  }
2037 
2038  // vertical page breaks
2039  if (!empty($vbreaks)) {
2040  // 1000 vertical pagebreaks appears to be an internal Excel 5 limit.
2041  // It is slightly higher in Excel 97/200, approx. 1026
2042  $vbreaks = array_slice($vbreaks, 0, 1000);
2043 
2044  // Sort and filter array of page breaks
2045  sort($vbreaks, SORT_NUMERIC);
2046  if ($vbreaks[0] == 0) { // don't use first break if it's 0
2047  array_shift($vbreaks);
2048  }
2049 
2050  $record = 0x001a; // Record identifier
2051  $cbrk = count($vbreaks); // Number of page breaks
2052  $length = 2 + 6 * $cbrk; // Bytes to follow
2053 
2054  $header = pack('vv', $record, $length);
2055  $data = pack('v', $cbrk);
2056 
2057  // Append each page break
2058  foreach ($vbreaks as $vbreak) {
2059  $data .= pack('vvv', $vbreak, 0x0000, 0xffff);
2060  }
2061 
2062  $this->append($header . $data);
2063  }
2064  }
2065 
2069  private function writeProtect(): void
2070  {
2071  // Exit unless sheet protection has been specified
2072  if (!$this->phpSheet->getProtection()->getSheet()) {
2073  return;
2074  }
2075 
2076  $record = 0x0012; // Record identifier
2077  $length = 0x0002; // Bytes to follow
2078 
2079  $fLock = 1; // Worksheet is protected
2080 
2081  $header = pack('vv', $record, $length);
2082  $data = pack('v', $fLock);
2083 
2084  $this->append($header . $data);
2085  }
2086 
2090  private function writeScenProtect(): void
2091  {
2092  // Exit if sheet protection is not active
2093  if (!$this->phpSheet->getProtection()->getSheet()) {
2094  return;
2095  }
2096 
2097  // Exit if scenarios are not protected
2098  if (!$this->phpSheet->getProtection()->getScenarios()) {
2099  return;
2100  }
2101 
2102  $record = 0x00DD; // Record identifier
2103  $length = 0x0002; // Bytes to follow
2104 
2105  $header = pack('vv', $record, $length);
2106  $data = pack('v', 1);
2107 
2108  $this->append($header . $data);
2109  }
2110 
2114  private function writeObjectProtect(): void
2115  {
2116  // Exit if sheet protection is not active
2117  if (!$this->phpSheet->getProtection()->getSheet()) {
2118  return;
2119  }
2120 
2121  // Exit if objects are not protected
2122  if (!$this->phpSheet->getProtection()->getObjects()) {
2123  return;
2124  }
2125 
2126  $record = 0x0063; // Record identifier
2127  $length = 0x0002; // Bytes to follow
2128 
2129  $header = pack('vv', $record, $length);
2130  $data = pack('v', 1);
2131 
2132  $this->append($header . $data);
2133  }
2134 
2138  private function writePassword(): void
2139  {
2140  // Exit unless sheet protection and password have been specified
2141  if (!$this->phpSheet->getProtection()->getSheet() || !$this->phpSheet->getProtection()->getPassword()) {
2142  return;
2143  }
2144 
2145  $record = 0x0013; // Record identifier
2146  $length = 0x0002; // Bytes to follow
2147 
2148  $wPassword = hexdec($this->phpSheet->getProtection()->getPassword()); // Encoded password
2149 
2150  $header = pack('vv', $record, $length);
2151  $data = pack('v', $wPassword);
2152 
2153  $this->append($header . $data);
2154  }
2155 
2167  public function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1): void
2168  {
2169  $bitmap_array = (is_resource($bitmap) || $bitmap instanceof GdImage
2170  ? $this->processBitmapGd($bitmap)
2171  : $this->processBitmap($bitmap));
2172  [$width, $height, $size, $data] = $bitmap_array;
2173 
2174  // Scale the frame of the image.
2175  $width *= $scale_x;
2176  $height *= $scale_y;
2177 
2178  // Calculate the vertices of the image and write the OBJ record
2179  $this->positionImage($col, $row, $x, $y, $width, $height);
2180 
2181  // Write the IMDATA record to store the bitmap data
2182  $record = 0x007f;
2183  $length = 8 + $size;
2184  $cf = 0x09;
2185  $env = 0x01;
2186  $lcb = $size;
2187 
2188  $header = pack('vvvvV', $record, $length, $cf, $env, $lcb);
2189  $this->append($header . $data);
2190  }
2191 
2242  public function positionImage($col_start, $row_start, $x1, $y1, $width, $height): void
2243  {
2244  // Initialise end cell to the same as the start cell
2245  $col_end = $col_start; // Col containing lower right corner of object
2246  $row_end = $row_start; // Row containing bottom right corner of object
2247 
2248  // Zero the specified offset if greater than the cell dimensions
2249  if ($x1 >= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1))) {
2250  $x1 = 0;
2251  }
2252  if ($y1 >= Xls::sizeRow($this->phpSheet, $row_start + 1)) {
2253  $y1 = 0;
2254  }
2255 
2256  $width = $width + $x1 - 1;
2257  $height = $height + $y1 - 1;
2258 
2259  // Subtract the underlying cell widths to find the end cell of the image
2260  while ($width >= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1))) {
2261  $width -= Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1));
2262  ++$col_end;
2263  }
2264 
2265  // Subtract the underlying cell heights to find the end cell of the image
2266  while ($height >= Xls::sizeRow($this->phpSheet, $row_end + 1)) {
2267  $height -= Xls::sizeRow($this->phpSheet, $row_end + 1);
2268  ++$row_end;
2269  }
2270 
2271  // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell
2272  // with zero eight or width.
2273  //
2274  if (Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1)) == 0) {
2275  return;
2276  }
2277  if (Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1)) == 0) {
2278  return;
2279  }
2280  if (Xls::sizeRow($this->phpSheet, $row_start + 1) == 0) {
2281  return;
2282  }
2283  if (Xls::sizeRow($this->phpSheet, $row_end + 1) == 0) {
2284  return;
2285  }
2286 
2287  // Convert the pixel values to the percentage value expected by Excel
2288  $x1 = $x1 / Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_start + 1)) * 1024;
2289  $y1 = $y1 / Xls::sizeRow($this->phpSheet, $row_start + 1) * 256;
2290  $x2 = $width / Xls::sizeCol($this->phpSheet, Coordinate::stringFromColumnIndex($col_end + 1)) * 1024; // Distance to right side of object
2291  $y2 = $height / Xls::sizeRow($this->phpSheet, $row_end + 1) * 256; // Distance to bottom of object
2292 
2293  $this->writeObjPicture($col_start, $x1, $row_start, $y1, $col_end, $x2, $row_end, $y2);
2294  }
2295 
2309  private function writeObjPicture($colL, $dxL, $rwT, $dyT, $colR, $dxR, $rwB, $dyB): void
2310  {
2311  $record = 0x005d; // Record identifier
2312  $length = 0x003c; // Bytes to follow
2313 
2314  $cObj = 0x0001; // Count of objects in file (set to 1)
2315  $OT = 0x0008; // Object type. 8 = Picture
2316  $id = 0x0001; // Object ID
2317  $grbit = 0x0614; // Option flags
2318 
2319  $cbMacro = 0x0000; // Length of FMLA structure
2320  $Reserved1 = 0x0000; // Reserved
2321  $Reserved2 = 0x0000; // Reserved
2322 
2323  $icvBack = 0x09; // Background colour
2324  $icvFore = 0x09; // Foreground colour
2325  $fls = 0x00; // Fill pattern
2326  $fAuto = 0x00; // Automatic fill
2327  $icv = 0x08; // Line colour
2328  $lns = 0xff; // Line style
2329  $lnw = 0x01; // Line weight
2330  $fAutoB = 0x00; // Automatic border
2331  $frs = 0x0000; // Frame style
2332  $cf = 0x0009; // Image format, 9 = bitmap
2333  $Reserved3 = 0x0000; // Reserved
2334  $cbPictFmla = 0x0000; // Length of FMLA structure
2335  $Reserved4 = 0x0000; // Reserved
2336  $grbit2 = 0x0001; // Option flags
2337  $Reserved5 = 0x0000; // Reserved
2338 
2339  $header = pack('vv', $record, $length);
2340  $data = pack('V', $cObj);
2341  $data .= pack('v', $OT);
2342  $data .= pack('v', $id);
2343  $data .= pack('v', $grbit);
2344  $data .= pack('v', $colL);
2345  $data .= pack('v', $dxL);
2346  $data .= pack('v', $rwT);
2347  $data .= pack('v', $dyT);
2348  $data .= pack('v', $colR);
2349  $data .= pack('v', $dxR);
2350  $data .= pack('v', $rwB);
2351  $data .= pack('v', $dyB);
2352  $data .= pack('v', $cbMacro);
2353  $data .= pack('V', $Reserved1);
2354  $data .= pack('v', $Reserved2);
2355  $data .= pack('C', $icvBack);
2356  $data .= pack('C', $icvFore);
2357  $data .= pack('C', $fls);
2358  $data .= pack('C', $fAuto);
2359  $data .= pack('C', $icv);
2360  $data .= pack('C', $lns);
2361  $data .= pack('C', $lnw);
2362  $data .= pack('C', $fAutoB);
2363  $data .= pack('v', $frs);
2364  $data .= pack('V', $cf);
2365  $data .= pack('v', $Reserved3);
2366  $data .= pack('v', $cbPictFmla);
2367  $data .= pack('v', $Reserved4);
2368  $data .= pack('v', $grbit2);
2369  $data .= pack('V', $Reserved5);
2370 
2371  $this->append($header . $data);
2372  }
2373 
2381  public function processBitmapGd($image)
2382  {
2383  $width = imagesx($image);
2384  $height = imagesy($image);
2385 
2386  $data = pack('Vvvvv', 0x000c, $width, $height, 0x01, 0x18);
2387  for ($j = $height; --$j;) {
2388  for ($i = 0; $i < $width; ++$i) {
2389  $color = imagecolorsforindex($image, imagecolorat($image, $i, $j));
2390  foreach (['red', 'green', 'blue'] as $key) {
2391  $color[$key] = $color[$key] + round((255 - $color[$key]) * $color['alpha'] / 127);
2392  }
2393  $data .= chr($color['blue']) . chr($color['green']) . chr($color['red']);
2394  }
2395  if (3 * $width % 4) {
2396  $data .= str_repeat("\x00", 4 - 3 * $width % 4);
2397  }
2398  }
2399 
2400  return [$width, $height, strlen($data), $data];
2401  }
2402 
2412  public function processBitmap($bitmap)
2413  {
2414  // Open file.
2415  $bmp_fd = @fopen($bitmap, 'rb');
2416  if (!$bmp_fd) {
2417  throw new WriterException("Couldn't import $bitmap");
2418  }
2419 
2420  // Slurp the file into a string.
2421  $data = fread($bmp_fd, filesize($bitmap));
2422 
2423  // Check that the file is big enough to be a bitmap.
2424  if (strlen($data) <= 0x36) {
2425  throw new WriterException("$bitmap doesn't contain enough data.\n");
2426  }
2427 
2428  // The first 2 bytes are used to identify the bitmap.
2429  $identity = unpack('A2ident', $data);
2430  if ($identity['ident'] != 'BM') {
2431  throw new WriterException("$bitmap doesn't appear to be a valid bitmap image.\n");
2432  }
2433 
2434  // Remove bitmap data: ID.
2435  $data = substr($data, 2);
2436 
2437  // Read and remove the bitmap size. This is more reliable than reading
2438  // the data size at offset 0x22.
2439  //
2440  $size_array = unpack('Vsa', substr($data, 0, 4));
2441  $size = $size_array['sa'];
2442  $data = substr($data, 4);
2443  $size -= 0x36; // Subtract size of bitmap header.
2444  $size += 0x0C; // Add size of BIFF header.
2445 
2446  // Remove bitmap data: reserved, offset, header length.
2447  $data = substr($data, 12);
2448 
2449  // Read and remove the bitmap width and height. Verify the sizes.
2450  $width_and_height = unpack('V2', substr($data, 0, 8));
2451  $width = $width_and_height[1];
2452  $height = $width_and_height[2];
2453  $data = substr($data, 8);
2454  if ($width > 0xFFFF) {
2455  throw new WriterException("$bitmap: largest image width supported is 65k.\n");
2456  }
2457  if ($height > 0xFFFF) {
2458  throw new WriterException("$bitmap: largest image height supported is 65k.\n");
2459  }
2460 
2461  // Read and remove the bitmap planes and bpp data. Verify them.
2462  $planes_and_bitcount = unpack('v2', substr($data, 0, 4));
2463  $data = substr($data, 4);
2464  if ($planes_and_bitcount[2] != 24) { // Bitcount
2465  throw new WriterException("$bitmap isn't a 24bit true color bitmap.\n");
2466  }
2467  if ($planes_and_bitcount[1] != 1) {
2468  throw new WriterException("$bitmap: only 1 plane supported in bitmap image.\n");
2469  }
2470 
2471  // Read and remove the bitmap compression. Verify compression.
2472  $compression = unpack('Vcomp', substr($data, 0, 4));
2473  $data = substr($data, 4);
2474 
2475  if ($compression['comp'] != 0) {
2476  throw new WriterException("$bitmap: compression not supported in bitmap image.\n");
2477  }
2478 
2479  // Remove bitmap data: data size, hres, vres, colours, imp. colours.
2480  $data = substr($data, 20);
2481 
2482  // Add the BITMAPCOREHEADER data
2483  $header = pack('Vvvvv', 0x000c, $width, $height, 0x01, 0x18);
2484  $data = $header . $data;
2485 
2486  return [$width, $height, $size, $data];
2487  }
2488 
2493  private function writeZoom(): void
2494  {
2495  // If scale is 100 we don't need to write a record
2496  if ($this->phpSheet->getSheetView()->getZoomScale() == 100) {
2497  return;
2498  }
2499 
2500  $record = 0x00A0; // Record identifier
2501  $length = 0x0004; // Bytes to follow
2502 
2503  $header = pack('vv', $record, $length);
2504  $data = pack('vv', $this->phpSheet->getSheetView()->getZoomScale(), 100);
2505  $this->append($header . $data);
2506  }
2507 
2513  public function getEscher()
2514  {
2515  return $this->escher;
2516  }
2517 
2523  public function setEscher(?\PhpOffice\PhpSpreadsheet\Shared\Escher $pValue = null): void
2524  {
2525  $this->escher = $pValue;
2526  }
2527 
2531  private function writeMsoDrawing(): void
2532  {
2533  // write the Escher stream if necessary
2534  if (isset($this->escher)) {
2535  $writer = new Escher($this->escher);
2536  $data = $writer->close();
2537  $spOffsets = $writer->getSpOffsets();
2538  $spTypes = $writer->getSpTypes();
2539  // write the neccesary MSODRAWING, OBJ records
2540 
2541  // split the Escher stream
2542  $spOffsets[0] = 0;
2543  $nm = count($spOffsets) - 1; // number of shapes excluding first shape
2544  for ($i = 1; $i <= $nm; ++$i) {
2545  // MSODRAWING record
2546  $record = 0x00EC; // Record identifier
2547 
2548  // chunk of Escher stream for one shape
2549  $dataChunk = substr($data, $spOffsets[$i - 1], $spOffsets[$i] - $spOffsets[$i - 1]);
2550 
2551  $length = strlen($dataChunk);
2552  $header = pack('vv', $record, $length);
2553 
2554  $this->append($header . $dataChunk);
2555 
2556  // OBJ record
2557  $record = 0x005D; // record identifier
2558  $objData = '';
2559 
2560  // ftCmo
2561  if ($spTypes[$i] == 0x00C9) {
2562  // Add ftCmo (common object data) subobject
2563  $objData .=
2564  pack(
2565  'vvvvvVVV',
2566  0x0015, // 0x0015 = ftCmo
2567  0x0012, // length of ftCmo data
2568  0x0014, // object type, 0x0014 = filter
2569  $i, // object id number, Excel seems to use 1-based index, local for the sheet
2570  0x2101, // option flags, 0x2001 is what OpenOffice.org uses
2571  0, // reserved
2572  0, // reserved
2573  0 // reserved
2574  );
2575 
2576  // Add ftSbs Scroll bar subobject
2577  $objData .= pack('vv', 0x00C, 0x0014);
2578  $objData .= pack('H*', '0000000000000000640001000A00000010000100');
2579  // Add ftLbsData (List box data) subobject
2580  $objData .= pack('vv', 0x0013, 0x1FEE);
2581  $objData .= pack('H*', '00000000010001030000020008005700');
2582  } else {
2583  // Add ftCmo (common object data) subobject
2584  $objData .=
2585  pack(
2586  'vvvvvVVV',
2587  0x0015, // 0x0015 = ftCmo
2588  0x0012, // length of ftCmo data
2589  0x0008, // object type, 0x0008 = picture
2590  $i, // object id number, Excel seems to use 1-based index, local for the sheet
2591  0x6011, // option flags, 0x6011 is what OpenOffice.org uses
2592  0, // reserved
2593  0, // reserved
2594  0 // reserved
2595  );
2596  }
2597 
2598  // ftEnd
2599  $objData .=
2600  pack(
2601  'vv',
2602  0x0000, // 0x0000 = ftEnd
2603  0x0000 // length of ftEnd data
2604  );
2605 
2606  $length = strlen($objData);
2607  $header = pack('vv', $record, $length);
2608  $this->append($header . $objData);
2609  }
2610  }
2611  }
2612 
2616  private function writeDataValidity(): void
2617  {
2618  // Datavalidation collection
2619  $dataValidationCollection = $this->phpSheet->getDataValidationCollection();
2620 
2621  // Write data validations?
2622  if (!empty($dataValidationCollection)) {
2623  // DATAVALIDATIONS record
2624  $record = 0x01B2; // Record identifier
2625  $length = 0x0012; // Bytes to follow
2626 
2627  $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records
2628  $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position
2629  $verPos = 0x00000000; // Vertical position of prompt box, if fixed position
2630  $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible
2631 
2632  $header = pack('vv', $record, $length);
2633  $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId, count($dataValidationCollection));
2634  $this->append($header . $data);
2635 
2636  // DATAVALIDATION records
2637  $record = 0x01BE; // Record identifier
2638 
2639  foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) {
2640  // options
2641  $options = 0x00000000;
2642 
2643  // data type
2644  $type = CellDataValidation::type($dataValidation);
2645 
2646  $options |= $type << 0;
2647 
2648  // error style
2649  $errorStyle = CellDataValidation::errorStyle($dataValidation);
2650 
2651  $options |= $errorStyle << 4;
2652 
2653  // explicit formula?
2654  if ($type == 0x03 && preg_match('/^\".*\"$/', $dataValidation->getFormula1())) {
2655  $options |= 0x01 << 7;
2656  }
2657 
2658  // empty cells allowed
2659  $options |= $dataValidation->getAllowBlank() << 8;
2660 
2661  // show drop down
2662  $options |= (!$dataValidation->getShowDropDown()) << 9;
2663 
2664  // show input message
2665  $options |= $dataValidation->getShowInputMessage() << 18;
2666 
2667  // show error message
2668  $options |= $dataValidation->getShowErrorMessage() << 19;
2669 
2670  // condition operator
2671  $operator = CellDataValidation::operator($dataValidation);
2672 
2673  $options |= $operator << 20;
2674 
2675  $data = pack('V', $options);
2676 
2677  // prompt title
2678  $promptTitle = $dataValidation->getPromptTitle() !== '' ?
2679  $dataValidation->getPromptTitle() : chr(0);
2680  $data .= StringHelper::UTF8toBIFF8UnicodeLong($promptTitle);
2681 
2682  // error title
2683  $errorTitle = $dataValidation->getErrorTitle() !== '' ?
2684  $dataValidation->getErrorTitle() : chr(0);
2685  $data .= StringHelper::UTF8toBIFF8UnicodeLong($errorTitle);
2686 
2687  // prompt text
2688  $prompt = $dataValidation->getPrompt() !== '' ?
2689  $dataValidation->getPrompt() : chr(0);
2690  $data .= StringHelper::UTF8toBIFF8UnicodeLong($prompt);
2691 
2692  // error text
2693  $error = $dataValidation->getError() !== '' ?
2694  $dataValidation->getError() : chr(0);
2695  $data .= StringHelper::UTF8toBIFF8UnicodeLong($error);
2696 
2697  // formula 1
2698  try {
2699  $formula1 = $dataValidation->getFormula1();
2700  if ($type == 0x03) { // list type
2701  $formula1 = str_replace(',', chr(0), $formula1);
2702  }
2703  $this->parser->parse($formula1);
2704  $formula1 = $this->parser->toReversePolish();
2705  $sz1 = strlen($formula1);
2706  } catch (PhpSpreadsheetException $e) {
2707  $sz1 = 0;
2708  $formula1 = '';
2709  }
2710  $data .= pack('vv', $sz1, 0x0000);
2711  $data .= $formula1;
2712 
2713  // formula 2
2714  try {
2715  $formula2 = $dataValidation->getFormula2();
2716  if ($formula2 === '') {
2717  throw new WriterException('No formula2');
2718  }
2719  $this->parser->parse($formula2);
2720  $formula2 = $this->parser->toReversePolish();
2721  $sz2 = strlen($formula2);
2722  } catch (PhpSpreadsheetException $e) {
2723  $sz2 = 0;
2724  $formula2 = '';
2725  }
2726  $data .= pack('vv', $sz2, 0x0000);
2727  $data .= $formula2;
2728 
2729  // cell range address list
2730  $data .= pack('v', 0x0001);
2731  $data .= $this->writeBIFF8CellRangeAddressFixed($cellCoordinate);
2732 
2733  $length = strlen($data);
2734  $header = pack('vv', $record, $length);
2735 
2736  $this->append($header . $data);
2737  }
2738  }
2739  }
2740 
2744  private function writePageLayoutView(): void
2745  {
2746  $record = 0x088B; // Record identifier
2747  $length = 0x0010; // Bytes to follow
2748 
2749  $rt = 0x088B; // 2
2750  $grbitFrt = 0x0000; // 2
2751  $reserved = 0x0000000000000000; // 8
2752  $wScalvePLV = $this->phpSheet->getSheetView()->getZoomScale(); // 2
2753 
2754  // The options flags that comprise $grbit
2755  if ($this->phpSheet->getSheetView()->getView() == SheetView::SHEETVIEW_PAGE_LAYOUT) {
2756  $fPageLayoutView = 1;
2757  } else {
2758  $fPageLayoutView = 0;
2759  }
2760  $fRulerVisible = 0;
2761  $fWhitespaceHidden = 0;
2762 
2763  $grbit = $fPageLayoutView; // 2
2764  $grbit |= $fRulerVisible << 1;
2765  $grbit |= $fWhitespaceHidden << 3;
2766 
2767  $header = pack('vv', $record, $length);
2768  $data = pack('vvVVvv', $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit);
2769  $this->append($header . $data);
2770  }
2771 
2775  private function writeCFRule(Conditional $conditional): void
2776  {
2777  $record = 0x01B1; // Record identifier
2778  $type = null; // Type of the CF
2779  $operatorType = null; // Comparison operator
2780 
2781  if ($conditional->getConditionType() == Conditional::CONDITION_EXPRESSION) {
2782  $type = 0x02;
2783  $operatorType = 0x00;
2784  } elseif ($conditional->getConditionType() == Conditional::CONDITION_CELLIS) {
2785  $type = 0x01;
2786 
2787  switch ($conditional->getOperatorType()) {
2789  $operatorType = 0x00;
2790 
2791  break;
2793  $operatorType = 0x03;
2794 
2795  break;
2797  $operatorType = 0x05;
2798 
2799  break;
2801  $operatorType = 0x07;
2802 
2803  break;
2805  $operatorType = 0x06;
2806 
2807  break;
2809  $operatorType = 0x08;
2810 
2811  break;
2813  $operatorType = 0x04;
2814 
2815  break;
2817  $operatorType = 0x01;
2818 
2819  break;
2820  // not OPERATOR_NOTBETWEEN 0x02
2821  }
2822  }
2823 
2824  // $szValue1 : size of the formula data for first value or formula
2825  // $szValue2 : size of the formula data for second value or formula
2826  $arrConditions = $conditional->getConditions();
2827  $numConditions = count($arrConditions);
2828  if ($numConditions == 1) {
2829  $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
2830  $szValue2 = 0x0000;
2831  $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
2832  $operand2 = null;
2833  } elseif ($numConditions == 2 && ($conditional->getOperatorType() == Conditional::OPERATOR_BETWEEN)) {
2834  $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000);
2835  $szValue2 = ($arrConditions[1] <= 65535 ? 3 : 0x0000);
2836  $operand1 = pack('Cv', 0x1E, $arrConditions[0]);
2837  $operand2 = pack('Cv', 0x1E, $arrConditions[1]);
2838  } else {
2839  $szValue1 = 0x0000;
2840  $szValue2 = 0x0000;
2841  $operand1 = null;
2842  $operand2 = null;
2843  }
2844 
2845  // $flags : Option flags
2846  // Alignment
2847  $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() === null ? 1 : 0);
2848  $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() === null ? 1 : 0);
2849  $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() === false ? 1 : 0);
2850  $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() === null ? 1 : 0);
2851  $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() === 0 ? 1 : 0);
2852  $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() === false ? 1 : 0);
2853  if ($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0) {
2854  $bFormatAlign = 1;
2855  } else {
2856  $bFormatAlign = 0;
2857  }
2858  // Protection
2859  $bProtLocked = ($conditional->getStyle()->getProtection()->getLocked() == null ? 1 : 0);
2860  $bProtHidden = ($conditional->getStyle()->getProtection()->getHidden() == null ? 1 : 0);
2861  if ($bProtLocked == 0 || $bProtHidden == 0) {
2862  $bFormatProt = 1;
2863  } else {
2864  $bFormatProt = 0;
2865  }
2866  // Border
2867  $bBorderLeft = ($conditional->getStyle()->getBorders()->getLeft()->getColor()->getARGB() == Color::COLOR_BLACK
2868  && $conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0);
2869  $bBorderRight = ($conditional->getStyle()->getBorders()->getRight()->getColor()->getARGB() == Color::COLOR_BLACK
2870  && $conditional->getStyle()->getBorders()->getRight()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0);
2871  $bBorderTop = ($conditional->getStyle()->getBorders()->getTop()->getColor()->getARGB() == Color::COLOR_BLACK
2872  && $conditional->getStyle()->getBorders()->getTop()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0);
2873  $bBorderBottom = ($conditional->getStyle()->getBorders()->getBottom()->getColor()->getARGB() == Color::COLOR_BLACK
2874  && $conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() == Border::BORDER_NONE ? 1 : 0);
2875  if ($bBorderLeft == 0 || $bBorderRight == 0 || $bBorderTop == 0 || $bBorderBottom == 0) {
2876  $bFormatBorder = 1;
2877  } else {
2878  $bFormatBorder = 0;
2879  }
2880  // Pattern
2881  $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() === null ? 0 : 1);
2882  $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() == null ? 0 : 1);
2883  $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() == null ? 0 : 1);
2884  if ($bFillStyle == 0 || $bFillColor == 0 || $bFillColorBg == 0) {
2885  $bFormatFill = 1;
2886  } else {
2887  $bFormatFill = 0;
2888  }
2889  // Font
2890  if (
2891  $conditional->getStyle()->getFont()->getName() !== null
2892  || $conditional->getStyle()->getFont()->getSize() !== null
2893  || $conditional->getStyle()->getFont()->getBold() !== null
2894  || $conditional->getStyle()->getFont()->getItalic() !== null
2895  || $conditional->getStyle()->getFont()->getSuperscript() !== null
2896  || $conditional->getStyle()->getFont()->getSubscript() !== null
2897  || $conditional->getStyle()->getFont()->getUnderline() !== null
2898  || $conditional->getStyle()->getFont()->getStrikethrough() !== null
2899  || $conditional->getStyle()->getFont()->getColor()->getARGB() != null
2900  ) {
2901  $bFormatFont = 1;
2902  } else {
2903  $bFormatFont = 0;
2904  }
2905  // Alignment
2906  $flags = 0;
2907  $flags |= (1 == $bAlignHz ? 0x00000001 : 0);
2908  $flags |= (1 == $bAlignVt ? 0x00000002 : 0);
2909  $flags |= (1 == $bAlignWrapTx ? 0x00000004 : 0);
2910  $flags |= (1 == $bTxRotation ? 0x00000008 : 0);
2911  // Justify last line flag
2912  $flags |= (1 == 1 ? 0x00000010 : 0);
2913  $flags |= (1 == $bIndent ? 0x00000020 : 0);
2914  $flags |= (1 == $bShrinkToFit ? 0x00000040 : 0);
2915  // Default
2916  $flags |= (1 == 1 ? 0x00000080 : 0);
2917  // Protection
2918  $flags |= (1 == $bProtLocked ? 0x00000100 : 0);
2919  $flags |= (1 == $bProtHidden ? 0x00000200 : 0);
2920  // Border
2921  $flags |= (1 == $bBorderLeft ? 0x00000400 : 0);
2922  $flags |= (1 == $bBorderRight ? 0x00000800 : 0);
2923  $flags |= (1 == $bBorderTop ? 0x00001000 : 0);
2924  $flags |= (1 == $bBorderBottom ? 0x00002000 : 0);
2925  $flags |= (1 == 1 ? 0x00004000 : 0); // Top left to Bottom right border
2926  $flags |= (1 == 1 ? 0x00008000 : 0); // Bottom left to Top right border
2927  // Pattern
2928  $flags |= (1 == $bFillStyle ? 0x00010000 : 0);
2929  $flags |= (1 == $bFillColor ? 0x00020000 : 0);
2930  $flags |= (1 == $bFillColorBg ? 0x00040000 : 0);
2931  $flags |= (1 == 1 ? 0x00380000 : 0);
2932  // Font
2933  $flags |= (1 == $bFormatFont ? 0x04000000 : 0);
2934  // Alignment:
2935  $flags |= (1 == $bFormatAlign ? 0x08000000 : 0);
2936  // Border
2937  $flags |= (1 == $bFormatBorder ? 0x10000000 : 0);
2938  // Pattern
2939  $flags |= (1 == $bFormatFill ? 0x20000000 : 0);
2940  // Protection
2941  $flags |= (1 == $bFormatProt ? 0x40000000 : 0);
2942  // Text direction
2943  $flags |= (1 == 0 ? 0x80000000 : 0);
2944 
2945  $dataBlockFont = null;
2946  $dataBlockAlign = null;
2947  $dataBlockBorder = null;
2948  $dataBlockFill = null;
2949 
2950  // Data Blocks
2951  if ($bFormatFont == 1) {
2952  // Font Name
2953  if ($conditional->getStyle()->getFont()->getName() === null) {
2954  $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
2955  $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000);
2956  } else {
2957  $dataBlockFont = StringHelper::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName());
2958  }
2959  // Font Size
2960  if ($conditional->getStyle()->getFont()->getSize() === null) {
2961  $dataBlockFont .= pack('V', 20 * 11);
2962  } else {
2963  $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize());
2964  }
2965  // Font Options
2966  $dataBlockFont .= pack('V', 0);
2967  // Font weight
2968  if ($conditional->getStyle()->getFont()->getBold() === true) {
2969  $dataBlockFont .= pack('v', 0x02BC);
2970  } else {
2971  $dataBlockFont .= pack('v', 0x0190);
2972  }
2973  // Escapement type
2974  if ($conditional->getStyle()->getFont()->getSubscript() === true) {
2975  $dataBlockFont .= pack('v', 0x02);
2976  $fontEscapement = 0;
2977  } elseif ($conditional->getStyle()->getFont()->getSuperscript() === true) {
2978  $dataBlockFont .= pack('v', 0x01);
2979  $fontEscapement = 0;
2980  } else {
2981  $dataBlockFont .= pack('v', 0x00);
2982  $fontEscapement = 1;
2983  }
2984  // Underline type
2985  switch ($conditional->getStyle()->getFont()->getUnderline()) {
2986  case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_NONE:
2987  $dataBlockFont .= pack('C', 0x00);
2988  $fontUnderline = 0;
2989 
2990  break;
2991  case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLE:
2992  $dataBlockFont .= pack('C', 0x02);
2993  $fontUnderline = 0;
2994 
2995  break;
2996  case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_DOUBLEACCOUNTING:
2997  $dataBlockFont .= pack('C', 0x22);
2998  $fontUnderline = 0;
2999 
3000  break;
3001  case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLE:
3002  $dataBlockFont .= pack('C', 0x01);
3003  $fontUnderline = 0;
3004 
3005  break;
3006  case \PhpOffice\PhpSpreadsheet\Style\Font::UNDERLINE_SINGLEACCOUNTING:
3007  $dataBlockFont .= pack('C', 0x21);
3008  $fontUnderline = 0;
3009 
3010  break;
3011  default:
3012  $dataBlockFont .= pack('C', 0x00);
3013  $fontUnderline = 1;
3014 
3015  break;
3016  }
3017  // Not used (3)
3018  $dataBlockFont .= pack('vC', 0x0000, 0x00);
3019  // Font color index
3020  $colorIdx = Style\ColorMap::lookup($conditional->getStyle()->getFont()->getColor(), 0x00);
3021 
3022  $dataBlockFont .= pack('V', $colorIdx);
3023  // Not used (4)
3024  $dataBlockFont .= pack('V', 0x00000000);
3025  // Options flags for modified font attributes
3026  $optionsFlags = 0;
3027  $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() === null ? 1 : 0);
3028  $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0);
3029  $optionsFlags |= (1 == 1 ? 0x00000008 : 0);
3030  $optionsFlags |= (1 == 1 ? 0x00000010 : 0);
3031  $optionsFlags |= (1 == 0 ? 0x00000020 : 0);
3032  $optionsFlags |= (1 == 1 ? 0x00000080 : 0);
3033  $dataBlockFont .= pack('V', $optionsFlags);
3034  // Escapement type
3035  $dataBlockFont .= pack('V', $fontEscapement);
3036  // Underline type
3037  $dataBlockFont .= pack('V', $fontUnderline);
3038  // Always
3039  $dataBlockFont .= pack('V', 0x00000000);
3040  // Always
3041  $dataBlockFont .= pack('V', 0x00000000);
3042  // Not used (8)
3043  $dataBlockFont .= pack('VV', 0x00000000, 0x00000000);
3044  // Always
3045  $dataBlockFont .= pack('v', 0x0001);
3046  }
3047  if ($bFormatAlign === 1) {
3048  // Alignment and text break
3049  $blockAlign = Style\CellAlignment::horizontal($conditional->getStyle()->getAlignment());
3050  $blockAlign |= Style\CellAlignment::wrap($conditional->getStyle()->getAlignment()) << 3;
3051  $blockAlign |= Style\CellAlignment::vertical($conditional->getStyle()->getAlignment()) << 4;
3052  $blockAlign |= 0 << 7;
3053 
3054  // Text rotation angle
3055  $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation();
3056 
3057  // Indentation
3058  $blockIndent = $conditional->getStyle()->getAlignment()->getIndent();
3059  if ($conditional->getStyle()->getAlignment()->getShrinkToFit() === true) {
3060  $blockIndent |= 1 << 4;
3061  } else {
3062  $blockIndent |= 0 << 4;
3063  }
3064  $blockIndent |= 0 << 6;
3065 
3066  // Relative indentation
3067  $blockIndentRelative = 255;
3068 
3069  $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000);
3070  }
3071  if ($bFormatBorder === 1) {
3072  $blockLineStyle = Style\CellBorder::style($conditional->getStyle()->getBorders()->getLeft());
3073  $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getRight()) << 4;
3074  $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getTop()) << 8;
3075  $blockLineStyle |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getBottom()) << 12;
3076 
3077  // TODO writeCFRule() => $blockLineStyle => Index Color for left line
3078  // TODO writeCFRule() => $blockLineStyle => Index Color for right line
3079  // TODO writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off
3080  // TODO writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off
3081  $blockColor = 0;
3082  // TODO writeCFRule() => $blockColor => Index Color for top line
3083  // TODO writeCFRule() => $blockColor => Index Color for bottom line
3084  // TODO writeCFRule() => $blockColor => Index Color for diagonal line
3085  $blockColor |= Style\CellBorder::style($conditional->getStyle()->getBorders()->getDiagonal()) << 21;
3086  $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor);
3087  }
3088  if ($bFormatFill === 1) {
3089  // Fill Pattern Style
3090  $blockFillPatternStyle = Style\CellFill::style($conditional->getStyle()->getFill());
3091  // Background Color
3092  $colorIdxBg = Style\ColorMap::lookup($conditional->getStyle()->getFill()->getStartColor(), 0x41);
3093  // Foreground Color
3094  $colorIdxFg = Style\ColorMap::lookup($conditional->getStyle()->getFill()->getEndColor(), 0x40);
3095 
3096  $dataBlockFill = pack('v', $blockFillPatternStyle);
3097  $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7));
3098  }
3099 
3100  $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000);
3101  if ($bFormatFont === 1) { // Block Formatting : OK
3102  $data .= $dataBlockFont;
3103  }
3104  if ($bFormatAlign === 1) {
3105  $data .= $dataBlockAlign;
3106  }
3107  if ($bFormatBorder === 1) {
3108  $data .= $dataBlockBorder;
3109  }
3110  if ($bFormatFill === 1) { // Block Formatting : OK
3111  $data .= $dataBlockFill;
3112  }
3113  if ($bFormatProt == 1) {
3114  $data .= $this->getDataBlockProtection($conditional);
3115  }
3116  if ($operand1 !== null) {
3117  $data .= $operand1;
3118  }
3119  if ($operand2 !== null) {
3120  $data .= $operand2;
3121  }
3122  $header = pack('vv', $record, strlen($data));
3123  $this->append($header . $data);
3124  }
3125 
3129  private function writeCFHeader(): void
3130  {
3131  $record = 0x01B0; // Record identifier
3132  $length = 0x0016; // Bytes to follow
3133 
3134  $numColumnMin = null;
3135  $numColumnMax = null;
3136  $numRowMin = null;
3137  $numRowMax = null;
3138  $arrConditional = [];
3139  foreach ($this->phpSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) {
3140  foreach ($conditionalStyles as $conditional) {
3141  if (
3142  $conditional->getConditionType() == Conditional::CONDITION_EXPRESSION ||
3143  $conditional->getConditionType() == Conditional::CONDITION_CELLIS
3144  ) {
3145  if (!in_array($conditional->getHashCode(), $arrConditional)) {
3146  $arrConditional[] = $conditional->getHashCode();
3147  }
3148  // Cells
3149  $rangeCoordinates = Coordinate::rangeBoundaries($cellCoordinate);
3150  if ($numColumnMin === null || ($numColumnMin > $rangeCoordinates[0][0])) {
3151  $numColumnMin = $rangeCoordinates[0][0];
3152  }
3153  if ($numColumnMax === null || ($numColumnMax < $rangeCoordinates[1][0])) {
3154  $numColumnMax = $rangeCoordinates[1][0];
3155  }
3156  if ($numRowMin === null || ($numRowMin > $rangeCoordinates[0][1])) {
3157  $numRowMin = (int) $rangeCoordinates[0][1];
3158  }
3159  if ($numRowMax === null || ($numRowMax < $rangeCoordinates[1][1])) {
3160  $numRowMax = (int) $rangeCoordinates[1][1];
3161  }
3162  }
3163  }
3164  }
3165  $needRedraw = 1;
3166  $cellRange = pack('vvvv', $numRowMin - 1, $numRowMax - 1, $numColumnMin - 1, $numColumnMax - 1);
3167 
3168  $header = pack('vv', $record, $length);
3169  $data = pack('vv', count($arrConditional), $needRedraw);
3170  $data .= $cellRange;
3171  $data .= pack('v', 0x0001);
3172  $data .= $cellRange;
3173  $this->append($header . $data);
3174  }
3175 
3176  private function getDataBlockProtection(Conditional $conditional): int
3177  {
3178  $dataBlockProtection = 0;
3179  if ($conditional->getStyle()->getProtection()->getLocked() == Protection::PROTECTION_PROTECTED) {
3180  $dataBlockProtection = 1;
3181  }
3182  if ($conditional->getStyle()->getProtection()->getHidden() == Protection::PROTECTION_PROTECTED) {
3183  $dataBlockProtection = 1 << 1;
3184  }
3185 
3186  return $dataBlockProtection;
3187  }
3188 }
if(preg_match('/^ $link_type[A-Z]:/', $url))
Definition: Worksheet.php:1092
writeDefcol()
Write BIFF record DEFCOLWIDTH if COLINFO records are in use.
Definition: Worksheet.php:1297
writeStringRecord($stringValue)
Write a STRING record.
Definition: Worksheet.php:907
static operator(DataValidation $dataValidation)
static splitRange($pRange)
Split range into coordinate strings.
Definition: Coordinate.php:140
writeBreaks()
Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records.
Definition: Worksheet.php:1986
writeUrl($row, $col, $url)
Write a hyperlink.
Definition: Worksheet.php:933
static static getErrorCodes()
Get list of error codes.
Definition: DataType.php:40
$size
Definition: RandomTest.php:84
processBitmapGd($image)
Convert a GD-image into the internal format.
Definition: Worksheet.php:2381
writeDimensions()
Writes Excel DIMENSIONS to define the area in which there is data.
Definition: Worksheet.php:1209
writeString($row, $col, $str, $xfIndex)
Write a LABELSST record or a LABEL record.
Definition: Worksheet.php:690
writeUrlExternal($row1, $col1, $row2, $col2, $url)
Write links to external directory names such as &#39;c:.xls&#39;, c:.xls::Sheet1!A1&#39;, &#39;../../foo.xls&#39;.
Definition: Worksheet.php:1067
writeHeader()
Store the header caption BIFF record.
Definition: Worksheet.php:1685
$type
writeWsbool()
Write the WSBOOL BIFF record, mainly for fit-to-page.
Definition: Worksheet.php:1951
static countCharacters($value, $enc='UTF-8')
Get character count.
writeColinfo($col_array)
Write BIFF record COLINFO to define column widths.
Definition: Worksheet.php:1323
__construct(&$str_total, &$str_unique, &$str_table, &$colors, Parser $parser, $preCalculateFormulas, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet $phpSheet)
Constructor.
Definition: Worksheet.php:223
writeNumber($row, $col, $num, $xfIndex)
Write a double to the specified row and column (zero indexed).
Definition: Worksheet.php:665
static getDefaultColumnWidthByFont(\PhpOffice\PhpSpreadsheet\Style\Font $font, $pPixels=false)
Get the effective column width for columns without a column dimension or column with width -1 For exa...
Definition: Font.php:554
writeFooter()
Store the footer caption BIFF record.
Definition: Worksheet.php:1709
if(!array_key_exists('StateId', $_REQUEST)) $id
positionImage($col_start, $row_start, $x1, $y1, $width, $height)
Calculate the vertices that define the position of the image as required by the OBJ record...
Definition: Worksheet.php:2242
writeRichTextString($row, $col, $str, $xfIndex, $arrcRun)
Write a LABELSST record or a LABEL record.
Definition: Worksheet.php:705
writeAutoFilterInfo()
Write the AUTOFILTERINFO BIFF record.
Definition: Worksheet.php:1887
writeSheetLayout()
Write SHEETLAYOUT record.
Definition: Worksheet.php:1458
static errorStyle(DataValidation $dataValidation)
static UTF8toBIFF8UnicodeShort($value, $arrcRuns=[])
Converts a UTF-8 string into BIFF8 Unicode string data (8-bit string length) Writes the string using ...
storeEof()
Writes Excel EOF record to indicate the end of a BIFF stream.
Definition: BIFFwriter.php:166
static static lookup(Color $color, int $defaultIndex=0x00)
Definition: ColorMap.php:71
writeLabelSst($row, $col, $str, $xfIndex)
Write a string to the specified row and column (zero indexed).
Definition: Worksheet.php:732
writeZoom()
Store the window zoom factor.
Definition: Worksheet.php:2493
writePrintHeaders()
Write the PRINTHEADERS BIFF record.
Definition: Worksheet.php:1840
writeWindow2()
Write BIFF record Window2.
Definition: Worksheet.php:1223
writeUrlInternal($row1, $col1, $row2, $col2, $url)
Used to write internal reference hyperlinks such as "Sheet1!A1".
Definition: Worksheet.php:1019
writePanes()
Writes the Excel BIFF PANE record.
Definition: Worksheet.php:1580
$env
writeMsoDrawing()
Write MSODRAWING record.
Definition: Worksheet.php:2531
$y
Definition: example_007.php:83
writeSheetProtection()
Write SHEETPROTECTION.
Definition: Worksheet.php:1485
writeHcenter()
Store the horizontal centering HCENTER BIFF record.
Definition: Worksheet.php:1733
writeBIFF8CellRangeAddressFixed($range)
Write a cell range address in BIFF8 always fixed range See section 2.5.14 in OpenOffice.org&#39;s Documentation of the Microsoft Excel File Format.
Definition: Worksheet.php:583
writePassword()
Write the worksheet PASSWORD record.
Definition: Worksheet.php:2138
insertBitmap($row, $col, $bitmap, $x=0, $y=0, $scale_x=1, $scale_y=1)
Insert a 24bit bitmap image in a worksheet.
Definition: Worksheet.php:2167
writeFormula($row, $col, $formula, $xfIndex, $calculatedValue)
Write a formula to the specified row and column (zero indexed).
Definition: Worksheet.php:826
printRowColHeaders($print=1)
Set the option to print the row and column headers on the printed page.
Definition: Worksheet.php:628
writeSetup()
Store the page setup SETUP BIFF record.
Definition: Worksheet.php:1625
static UTF8toBIFF8UnicodeLong($value)
Converts a UTF-8 string into BIFF8 Unicode string data (16-bit string length) Writes the string using...
append($data)
General storage function.
Definition: BIFFwriter.php:112
writeRangeProtection()
Write BIFF record RANGEPROTECTION.
Definition: Worksheet.php:1532
setEscher(?\PhpOffice\PhpSpreadsheet\Shared\Escher $pValue=null)
Set Escher object.
Definition: Worksheet.php:2523
static static error(string $errorCode)
Definition: ErrorCode.php:20
static indexesFromString(string $coordinates)
Get indexes from a string coordinates.
Definition: Coordinate.php:52
static convertEncoding($value, $to, $from)
Convert string from one encoding to another.
writeSelection()
Write BIFF record SELECTION.
Definition: Worksheet.php:1351
writeMarginRight()
Store the RIGHTMARGIN BIFF record.
Definition: Worksheet.php:1783
$row
writeCFRule(Conditional $conditional)
Write CFRule Record.
Definition: Worksheet.php:2775
writeRow($row, $height, $xfIndex, $hidden=false, $level=0)
This method is used to set the height and format for a row.
Definition: Worksheet.php:1160
storeBof($type)
Writes Excel BOF record to indicate the beginning of a stream or sub-stream in the BIFF file...
Definition: BIFFwriter.php:145
$password
Definition: cron.php:14
static coordinateFromString($pCoordinateString)
Coordinate from string.
Definition: Coordinate.php:32
writeMarginBottom()
Store the BOTTOMMARGIN BIFF record.
Definition: Worksheet.php:1821
writeMarginLeft()
Store the LEFTMARGIN BIFF record.
Definition: Worksheet.php:1764
writeMergedCells()
Store the MERGEDCELLS records for all ranges of merged cells.
Definition: Worksheet.php:1404
writeProtect()
Set the Biff PROTECT record to indicate that the worksheet is protected.
Definition: Worksheet.php:2069
static rangeBoundaries($pRange)
Calculate range boundaries.
Definition: Coordinate.php:187
writeUrlRange($row1, $col1, $row2, $col2, $url)
This is the more general form of writeUrl().
Definition: Worksheet.php:953
$i
Definition: disco.tpl.php:19
processBitmap($bitmap)
Convert a 24 bit bitmap into the modified internal format used by Windows.
Definition: Worksheet.php:2412
writeGridset()
Write the GRIDSET BIFF record.
Definition: Worksheet.php:1872
getData()
Retrieves data from memory in one chunk, or from disk sized chunks.
Definition: Worksheet.php:609
writePrintGridlines()
Write the PRINTGRIDLINES BIFF record.
Definition: Worksheet.php:1856
setOutline($visible=true, $symbols_below=true, $symbols_right=true, $auto_style=false)
This method sets the properties for outlining and grouping.
Definition: Worksheet.php:642
writeVcenter()
Store the vertical centering VCENTER BIFF record.
Definition: Worksheet.php:1749
writeUrlWeb($row1, $col1, $row2, $col2, $url)
Used to write http, ftp and mailto hyperlinks.
Definition: Worksheet.php:979
writeDefaultRowHeight()
Write BIFF record DEFAULTROWHEIGHT.
Definition: Worksheet.php:1275
writeBlank($row, $col, $xfIndex)
Write a blank cell to the specified row and column (zero indexed).
Definition: Worksheet.php:768
static columnIndexFromString($pString)
Column index from string.
Definition: Coordinate.php:265
$key
Definition: croninfo.php:18
$x
Definition: complexTest.php:9
static stringFromColumnIndex($columnIndex)
String from column index.
Definition: Coordinate.php:313
writeGuts()
Write the GUTS BIFF record.
Definition: Worksheet.php:1907
getDataBlockProtection(Conditional $conditional)
Definition: Worksheet.php:3176
writeMarginTop()
Store the TOPMARGIN BIFF record.
Definition: Worksheet.php:1802
writeDataValidity()
Store the DATAVALIDATIONS and DATAVALIDATION records.
Definition: Worksheet.php:2616
writeObjPicture($colL, $dxL, $rwT, $dyT, $colR, $dxR, $rwB, $dyB)
Store the OBJ record that precedes an IMDATA record.
Definition: Worksheet.php:2309
writeBoolErr($row, $col, $value, $isError, $xfIndex)
Write a boolean or an error type to the specified row and column (zero indexed).
Definition: Worksheet.php:791