private static function toCSSArray($style) { $style = str_replace("\r", "", $style); $style = str_replace("\n", "", $style); $temp = explode(';', $style); $style = array(); foreach ($temp as $item) { $item = explode(':', $item); if (strpos($item[1], 'px') !== false) { $item[1] = str_replace('px', '', $item[1]); } if (strpos($item[1], 'pt') !== false) { $item[1] = str_replace('pt', '', $item[1]); $item[1] = Shared_Font::fontSizeToPixels($item[1]); } if (strpos($item[1], 'in') !== false) { $item[1] = str_replace('in', '', $item[1]); $item[1] = Shared_Font::inchSizeToPixels($item[1]); } if (strpos($item[1], 'cm') !== false) { $item[1] = str_replace('cm', '', $item[1]); $item[1] = Shared_Font::centimeterSizeToPixels($item[1]); } $style[$item[0]] = $item[1]; } return $style; }
/** * Get font record data * * @return string */ public function writeFont() { $font_outline = 0; $font_shadow = 0; $icv = $this->_colorIndex; // Index to color palette if ($this->_font->getSuperScript()) { $sss = 1; } else { if ($this->_font->getSubScript()) { $sss = 2; } else { $sss = 0; } } $bFamily = 0; // Font family $bCharSet = Shared_Font::getCharsetFromFontName($this->_font->getName()); // Character set $record = 0x31; // Record identifier $reserved = 0x0; // Reserved $grbit = 0x0; // Font attributes if ($this->_font->getItalic()) { $grbit |= 0x2; } if ($this->_font->getStrikethrough()) { $grbit |= 0x8; } if ($font_outline) { $grbit |= 0x10; } if ($font_shadow) { $grbit |= 0x20; } if ($this->_BIFFVersion == 0x500) { $data = pack("vvvvvCCCCC", $this->_font->getSize() * 20, $grbit, $icv, $this->_mapBold($this->_font->getBold()), $sss, $this->_mapUnderline($this->_font->getUnderline()), $bFamily, $bCharSet, $reserved, strlen($this->_font->getName())); $data .= $this->_font->getName(); } elseif ($this->_BIFFVersion == 0x600) { $data = pack("vvvvvCCCC", $this->_font->getSize() * 20, $grbit, $icv, $this->_mapBold($this->_font->getBold()), $sss, $this->_mapUnderline($this->_font->getUnderline()), $bFamily, $bCharSet, $reserved); $data .= Shared_String::UTF8toBIFF8UnicodeShort($this->_font->getName()); } $length = strlen($data); $header = pack("vv", $record, $length); return $header . $data; }
/** * Add data to the beginning of the workbook (note the reverse order) * and to the end of the workbook. * * @access public * @see Writer_Excel5_Workbook::storeWorkbook() */ function close() { $num_sheets = $this->_phpSheet->getParent()->getSheetCount(); // Write BOF record $this->_storeBof(0x10); // Write PRINTHEADERS $this->_writePrintHeaders(); // Write PRINTGRIDLINES $this->_writePrintGridlines(); // Write GRIDSET $this->_writeGridset(); // Calculate column widths $this->_phpSheet->calculateColumnWidths(); // Column dimensions $columnDimensions = $this->_phpSheet->getColumnDimensions(); for ($i = 0; $i < 256; ++$i) { $hidden = 0; $level = 0; $xfIndex = 15; // there are 15 cell style Xfs if ($this->_phpSheet->getDefaultColumnDimension()->getWidth() >= 0) { $width = $this->_phpSheet->getDefaultColumnDimension()->getWidth(); } else { $width = Shared_Font::getDefaultColumnWidthByFont($this->_phpSheet->getParent()->getDefaultStyle()->getFont()); } $columnLetter = Cell::stringFromColumnIndex($i); if (isset($columnDimensions[$columnLetter])) { $columnDimension = $columnDimensions[$columnLetter]; if ($columnDimension->getWidth() >= 0) { $width = $columnDimension->getWidth(); } $hidden = $columnDimension->getVisible() ? 0 : 1; $level = $columnDimension->getOutlineLevel(); $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs } // Components of _colinfo: // $firstcol first column on the range // $lastcol last column on the range // $width width to set // $xfIndex The optional cell style Xf index to apply to the columns // $hidden The optional hidden atribute // $level The optional outline level $this->_colinfo[] = array($i, $i, $width, $xfIndex, $hidden, $level); } // Write GUTS $this->_writeGuts(); // Write DEFAULTROWHEIGHT if ($this->_BIFF_version == 0x600) { $this->_writeDefaultRowHeight(); } // Write WSBOOL $this->_writeWsbool(); // Write horizontal and vertical page breaks $this->_writeBreaks(); // Write page header $this->_writeHeader(); // Write page footer $this->_writeFooter(); // Write page horizontal centering $this->_writeHcenter(); // Write page vertical centering $this->_writeVcenter(); // Write left margin $this->_writeMarginLeft(); // Write right margin $this->_writeMarginRight(); // Write top margin $this->_writeMarginTop(); // Write bottom margin $this->_writeMarginBottom(); // Write page setup $this->_writeSetup(); // Write sheet protection $this->_writeProtect(); // Write SCENPROTECT $this->_writeScenProtect(); // Write OBJECTPROTECT $this->_writeObjectProtect(); // Write sheet password $this->_writePassword(); // Write DEFCOLWIDTH record $this->_writeDefcol(); // Write the COLINFO records if they exist if (!empty($this->_colinfo)) { $colcount = count($this->_colinfo); for ($i = 0; $i < $colcount; ++$i) { $this->_writeColinfo($this->_colinfo[$i]); } } // Write EXTERNCOUNT of external references if ($this->_BIFF_version == 0x500) { $this->_writeExterncount($num_sheets); } // Write EXTERNSHEET references if ($this->_BIFF_version == 0x500) { for ($i = 0; $i < $num_sheets; ++$i) { $this->_writeExternsheet($this->_phpSheet->getParent()->getSheet($i)->getTitle()); } } // Write sheet dimensions $this->_writeDimensions(); // Row dimensions foreach ($this->_phpSheet->getRowDimensions() as $rowDimension) { $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs $this->_writeRow($rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, $rowDimension->getVisible() ? '0' : '1', $rowDimension->getOutlineLevel()); } // Write Cells foreach ($this->_phpSheet->getCellCollection() as $cellID) { $cell = $this->_phpSheet->getCell($cellID); $row = $cell->getRow() - 1; $column = Cell::columnIndexFromString($cell->getColumn()) - 1; // Don't break Excel! if ($row + 1 > 65536 or $column + 1 > 256) { break; } // Write cell value $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs if ($cell->getValue() instanceof RichText) { $this->_writeString($row, $column, $cell->getValue()->getPlainText(), $xfIndex); } else { switch ($cell->getDatatype()) { case Cell_DataType::TYPE_STRING: if ($cell->getValue() === '' or $cell->getValue() === null) { $this->_writeBlank($row, $column, $xfIndex); } else { $this->_writeString($row, $column, $cell->getValue(), $xfIndex); } break; case Cell_DataType::TYPE_FORMULA: $calculatedValue = $this->_preCalculateFormulas ? $cell->getCalculatedValue() : null; $this->_writeFormula($row, $column, $cell->getValue(), $xfIndex, $calculatedValue); break; case Cell_DataType::TYPE_BOOL: $this->_writeBoolErr($row, $column, $cell->getValue(), 0, $xfIndex); break; case Cell_DataType::TYPE_ERROR: $this->_writeBoolErr($row, $column, $this->_mapErrorCode($cell->getValue()), 1, $xfIndex); break; case Cell_DataType::TYPE_NUMERIC: $this->_writeNumber($row, $column, $cell->getValue(), $xfIndex); break; } } } // Append if ($this->_BIFF_version == 0x600) { $this->_writeMsoDrawing(); } $this->_writeWindow2(); $this->_writeZoom(); if ($this->_phpSheet->getFreezePane()) { $this->_writePanes(); } $this->_writeSelection(); $this->_writeMergedCells(); // Hyperlinks if ($this->_BIFF_version == 0x600) { foreach ($this->_phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) { list($column, $row) = Cell::coordinateFromString($coordinate); $url = $hyperlink->getUrl(); if (strpos($url, 'sheet://') !== false) { // internal to current workbook $url = str_replace('sheet://', 'internal:', $url); } else { if (preg_match('/^(http:|https:|ftp:|mailto:)/', $url)) { // URL // $url = $url; } else { // external (local file) $url = 'external:' . $url; } } $this->_writeUrl($row - 1, Cell::columnIndexFromString($column) - 1, $url); } } if ($this->_BIFF_version == 0x600) { $this->_writeDataValidity(); $this->_writeSheetLayout(); $this->_writeSheetProtection(); $this->_writeRangeProtection(); } $this->_storeEof(); }
/** * Set the path to the folder containing .ttf files. There should be a trailing slash. * Typical locations on variout some platforms: * <ul> * <li>C:/Windows/Fonts/</li> * <li>/usr/share/fonts/truetype/</li> * <li>~/.fonts/</li> * </ul> * * @param string $pValue */ public static function setTrueTypeFontPath($pValue = '') { self::$trueTypeFontPath = $pValue; }
/** * Calculate widths for auto-size columns * * @param boolean $calculateMergeCells Calculate merge cell width * @return Worksheet; */ public function calculateColumnWidths($calculateMergeCells = false) { // initialize $autoSizes array $autoSizes = array(); foreach ($this->getColumnDimensions() as $colDimension) { if ($colDimension->getAutoSize()) { $autoSizes[$colDimension->getColumnIndex()] = -1; } } // There is only something to do if there are some auto-size columns if (!empty($autoSizes)) { // build list of cells references that participate in a merge $isMergeCell = array(); foreach ($this->getMergeCells() as $cells) { foreach (Cell::extractAllCellReferencesInRange($cells) as $cellReference) { $isMergeCell[$cellReference] = true; } } // loop through all cells in the worksheet foreach ($this->getCellCollection(false) as $cellID) { $cell = $this->getCell($cellID); if (isset($autoSizes[$cell->getColumn()])) { // Determine width if cell does not participate in a merge if (!isset($isMergeCell[$cell->getCoordinate()])) { // Calculated value $cellValue = $cell->getCalculatedValue(); // To formatted string $cellValue = Style_NumberFormat::toFormattedString($cellValue, $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode()); $autoSizes[$cell->getColumn()] = max((double) $autoSizes[$cell->getColumn()], (double) Shared_Font::calculateColumnWidth($this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(), $cellValue, $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(), $this->getDefaultStyle()->getFont())); } } } // adjust column widths foreach ($autoSizes as $columnIndex => $width) { if ($width == -1) { $width = $this->getDefaultColumnDimension()->getWidth(); } $this->getColumnDimension($columnIndex)->setWidth($width); } } return $this; }
/** * Convert the height of a cell from user's units to pixels. By interpolation * the relationship is: y = 4/3x. If the height hasn't been set by the user we * use the default value. If the row is hidden we use a value of zero. * * @param Worksheet $sheet The sheet * @param integer $row The row index (1-based) * @return integer The width in pixels */ public static function sizeRow($sheet, $row = 1) { // default font of the workbook $font = $sheet->getParent()->getDefaultStyle()->getFont(); $rowDimensions = $sheet->getRowDimensions(); // first find the true row height in pixels (uncollapsed and unhidden) if (isset($rowDimensions[$row]) and $rowDimensions[$row]->getRowHeight() != -1) { // then we have a row dimension $rowDimension = $rowDimensions[$row]; $rowHeight = $rowDimension->getRowHeight(); $pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10 } else { if ($sheet->getDefaultRowDimension()->getRowHeight() != -1) { // then we have a default row dimension with explicit height $defaultRowDimension = $sheet->getDefaultRowDimension(); $rowHeight = $defaultRowDimension->getRowHeight(); $pixelRowHeight = Shared_Drawing::pointsToPixels($rowHeight); } else { // we don't even have any default row dimension. Height depends on default font $pointRowHeight = Shared_Font::getDefaultRowHeightByFont($font); $pixelRowHeight = Shared_Font::fontSizeToPixels($pointRowHeight); } } // now find the effective row height in pixels if (isset($rowDimensions[$row]) and !$rowDimensions[$row]->getVisible()) { $effectivePixelRowHeight = 0; } else { $effectivePixelRowHeight = $pixelRowHeight; } return $effectivePixelRowHeight; }
/** * Build CSS styles * * @param boolean $generateSurroundingHTML Generate surrounding HTML style? (html { }) * @return array * @throws Exception */ public function buildCSS($generateSurroundingHTML = true) { // PHPExcel object known? if (is_null($this->_phpExcel)) { throw new Exception('Internal PHPExcel object not set to an instance of an object.'); } // Cached? if (!is_null($this->_cssStyles)) { return $this->_cssStyles; } // Ensure that spans have been calculated if (!$this->_spansAreCalculated) { $this->_calculateSpans(); } // Construct CSS $css = array(); // Start styles if ($generateSurroundingHTML) { // html { } $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif'; $css['html']['font-size'] = '11pt'; $css['html']['background-color'] = 'white'; } // table { } $css['table']['border-collapse'] = 'collapse'; $css['table']['page-break-after'] = 'always'; // .gridlines td { } $css['.gridlines td']['border'] = '1px dotted black'; // .b {} $css['.b']['text-align'] = 'center'; // BOOL // .e {} $css['.e']['text-align'] = 'center'; // ERROR // .f {} $css['.f']['text-align'] = 'right'; // FORMULA // .inlineStr {} $css['.inlineStr']['text-align'] = 'left'; // INLINE // .n {} $css['.n']['text-align'] = 'right'; // NUMERIC // .s {} $css['.s']['text-align'] = 'left'; // STRING // Calculate cell style hashes foreach ($this->_phpExcel->getCellXfCollection() as $index => $style) { $css['td.style' . $index] = $this->_createCSSStyle($style); } // Fetch sheets $sheets = array(); if (is_null($this->_sheetIndex)) { $sheets = $this->_phpExcel->getAllSheets(); } else { $sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex); } // Build styles per sheet foreach ($sheets as $sheet) { // Calculate hash code $sheetIndex = $sheet->getParent()->getIndex($sheet); // Build styles // Calculate column widths $sheet->calculateColumnWidths(); // col elements, initialize $highestColumnIndex = Cell::columnIndexFromString($sheet->getHighestColumn()) - 1; for ($column = 0; $column <= $highestColumnIndex; ++$column) { $this->_columnWidths[$sheetIndex][$column] = 42; // approximation $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = '42pt'; } // col elements, loop through columnDimensions and set width foreach ($sheet->getColumnDimensions() as $columnDimension) { if (($width = Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth(), $this->_defaultFont)) >= 0) { $width = Shared_Drawing::pixelsToPoints($width); $column = Cell::columnIndexFromString($columnDimension->getColumnIndex()) - 1; $this->_columnWidths[$sheetIndex][$column] = $width; $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = $width . 'pt'; if ($columnDimension->getVisible() === false) { $css['table.sheet' . $sheetIndex . ' col.col' . $column]['visibility'] = 'collapse'; $css['table.sheet' . $sheetIndex . ' col.col' . $column]['*display'] = 'none'; // target IE6+7 } } } // Default row height $rowDimension = $sheet->getDefaultRowDimension(); // table.sheetN tr { } $css['table.sheet' . $sheetIndex . ' tr'] = array(); if ($rowDimension->getRowHeight() == -1) { $pt_height = Shared_Font::getDefaultRowHeightByFont($this->_phpExcel->getDefaultStyle()->getFont()); } else { $pt_height = $rowDimension->getRowHeight(); } $css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt'; if ($rowDimension->getVisible() === false) { $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none'; $css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden'; } // Calculate row heights foreach ($sheet->getRowDimensions() as $rowDimension) { $row = $rowDimension->getRowIndex() - 1; // table.sheetN tr.rowYYYYYY { } $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = array(); if ($rowDimension->getRowHeight() == -1) { $pt_height = Shared_Font::getDefaultRowHeightByFont($this->_phpExcel->getDefaultStyle()->getFont()); } else { $pt_height = $rowDimension->getRowHeight(); } $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'] = $pt_height . 'pt'; if ($rowDimension->getVisible() === false) { $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['display'] = 'none'; $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['visibility'] = 'hidden'; } } } // Cache if (is_null($this->_cssStyles)) { $this->_cssStyles = $css; } // Return return $css; }