PHPExcel_Writer
[ class tree: PHPExcel_Writer ] [ index: PHPExcel_Writer ] [ all elements ]

Source for file HTML.php

Documentation is available at HTML.php

  1. <?php
  2. /**
  3.  * PHPExcel
  4.  *
  5.  * Copyright (c) 2006 - 2009 PHPExcel
  6.  *
  7.  * This library is free software; you can redistribute it and/or
  8.  * modify it under the terms of the GNU Lesser General Public
  9.  * License as published by the Free Software Foundation; either
  10.  * version 2.1 of the License, or (at your option) any later version.
  11.  *
  12.  * This library is distributed in the hope that it will be useful,
  13.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15.  * Lesser General Public License for more details.
  16.  *
  17.  * You should have received a copy of the GNU Lesser General Public
  18.  * License along with this library; if not, write to the Free Software
  19.  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
  20.  *
  21.  * @category   PHPExcel
  22.  * @package    PHPExcel_Writer
  23.  * @copyright  Copyright (c) 2006 - 2009 PHPExcel (http://www.codeplex.com/PHPExcel)
  24.  * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
  25.  * @version    1.7.0, 2009-08-10
  26.  */
  27.  
  28.  
  29. /** PHPExcel root directory */
  30. if (!defined('PHPEXCEL_ROOT')) {
  31.     /**
  32.      * @ignore
  33.      */
  34.     define('PHPEXCEL_ROOT'dirname(__FILE__'/../../');
  35. }
  36.  
  37. /** PHPExcel_IWriter */
  38. require_once PHPEXCEL_ROOT 'PHPExcel/Writer/IWriter.php';
  39.  
  40. /** PHPExcel_Cell */
  41. require_once PHPEXCEL_ROOT 'PHPExcel/Cell.php';
  42.  
  43. /** PHPExcel_RichText */
  44. require_once PHPEXCEL_ROOT 'PHPExcel/RichText.php';
  45.  
  46. /** PHPExcel_Shared_Drawing */
  47. require_once PHPEXCEL_ROOT 'PHPExcel/Shared/Drawing.php';
  48.  
  49. /** PHPExcel_Shared_String */
  50. require_once PHPEXCEL_ROOT 'PHPExcel/Shared/String.php';
  51.  
  52. /** PHPExcel_HashTable */
  53. require_once PHPEXCEL_ROOT 'PHPExcel/HashTable.php';
  54.  
  55.  
  56. /**
  57.  * PHPExcel_Writer_HTML
  58.  *
  59.  * @category   PHPExcel
  60.  * @package    PHPExcel_Writer
  61.  * @copyright  Copyright (c) 2006 - 2009 PHPExcel (http://www.codeplex.com/PHPExcel)
  62.  */
  63. class PHPExcel_Writer_HTML implements PHPExcel_Writer_IWriter {
  64.     /**
  65.      * PHPExcel object
  66.      *
  67.      * @var PHPExcel 
  68.      */
  69.     protected $_phpExcel;
  70.  
  71.     /**
  72.      * Sheet index to write
  73.      *
  74.      * @var int 
  75.      */
  76.     private $_sheetIndex;
  77.  
  78.     /**
  79.      * Pre-calculate formulas
  80.      *
  81.      * @var boolean 
  82.      */
  83.     private $_preCalculateFormulas = true;
  84.  
  85.     /**
  86.      * Images root
  87.      *
  88.      * @var string 
  89.      */
  90.     private $_imagesRoot = '.';
  91.     
  92.     /**
  93.      * Use inline CSS?
  94.      *
  95.      * @var boolean 
  96.      */
  97.     private $_useInlineCss = false;
  98.     
  99.     /**
  100.      * Array of CSS styles
  101.      *
  102.      * @var array 
  103.      */
  104.     private $_cssStyles = null;
  105.  
  106.     /**
  107.      * Array of column widths in points
  108.      *
  109.      * @var array 
  110.      */
  111.     private $_columnWidths = null;
  112.  
  113.     /**
  114.      * Default font size
  115.      *
  116.      * @var int 
  117.      */
  118.     private $_defaultFontSize;
  119.  
  120.     /**
  121.      * Is the current writer creating PDF?
  122.      *
  123.      * @var boolean 
  124.      */
  125.     protected $_isPdf = false;
  126.  
  127.     /**
  128.      * Create a new PHPExcel_Writer_HTML
  129.      *
  130.      * @param     PHPExcel    $phpExcel    PHPExcel object
  131.      */
  132.     public function __construct(PHPExcel $phpExcel{
  133.         $this->_phpExcel = $phpExcel;
  134.         $this->_defaultFontSize = $this->_phpExcel->getDefaultStyle()->getFont()->getSize();
  135.         $this->_sheetIndex = 0;
  136.         $this->_imagesRoot = '.';
  137.     }
  138.  
  139.     /**
  140.      * Save PHPExcel to file
  141.      *
  142.      * @param     string         $pFileName 
  143.      * @throws     Exception
  144.      */
  145.     public function save($pFilename null{
  146.         // garbage collect
  147.         $this->_phpExcel->garbageCollect();
  148.  
  149.         $saveArrayReturnType PHPExcel_Calculation::getArrayReturnType();
  150.         PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE);
  151.  
  152.         // Build CSS
  153.         $this->buildCSS(!$this->_useInlineCss);
  154.         
  155.         // Open file
  156.         $fileHandle fopen($pFilename'w');
  157.         if ($fileHandle === false{
  158.             throw new Exception("Could not open file $pFilename for writing.");
  159.         }
  160.  
  161.         // Write headers
  162.         fwrite($fileHandle$this->generateHTMLHeader(!$this->_useInlineCss));
  163.  
  164.         // Write data
  165.         fwrite($fileHandle$this->generateSheetData());
  166.  
  167.         // Write footer
  168.         fwrite($fileHandle$this->generateHTMLFooter());
  169.  
  170.         // Close file
  171.         fclose($fileHandle);
  172.  
  173.         PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType);
  174.     }
  175.  
  176.     /**
  177.      * Map VAlign
  178.      */
  179.     private function _mapVAlign($vAlign{
  180.         switch ($vAlign{
  181.             case PHPExcel_Style_Alignment::VERTICAL_BOTTOMreturn 'bottom';
  182.             case PHPExcel_Style_Alignment::VERTICAL_TOPreturn 'top';
  183.             case PHPExcel_Style_Alignment::VERTICAL_CENTER:
  184.             case PHPExcel_Style_Alignment::VERTICAL_JUSTIFYreturn 'middle';
  185.             defaultreturn 'baseline';
  186.         }
  187.     }
  188.  
  189.     /**
  190.      * Map HAlign
  191.      *
  192.      * @return string|false
  193.      */
  194.     private function _mapHAlign($hAlign{
  195.         switch ($hAlign{
  196.             case PHPExcel_Style_Alignment::HORIZONTAL_GENERALreturn false;
  197.             case PHPExcel_Style_Alignment::HORIZONTAL_LEFTreturn 'left';
  198.             case PHPExcel_Style_Alignment::HORIZONTAL_RIGHTreturn 'right';
  199.             case PHPExcel_Style_Alignment::HORIZONTAL_CENTERreturn 'center';
  200.             case PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFYreturn 'justify';
  201.             defaultreturn false;
  202.         }
  203.     }
  204.  
  205.     /**
  206.      * Map border style
  207.      */
  208.     private function _mapBorderStyle($borderStyle{
  209.         switch ($borderStyle{
  210.             case PHPExcel_Style_Border::BORDER_NONEreturn '0px';
  211.             case PHPExcel_Style_Border::BORDER_DASHEDreturn '1px dashed';
  212.             case PHPExcel_Style_Border::BORDER_DOTTEDreturn '1px dotted';
  213.             case PHPExcel_Style_Border::BORDER_THICKreturn '2px solid';
  214.             defaultreturn '1px solid'// map others to thin
  215.         }
  216.     }
  217.  
  218.     /**
  219.      * Get sheet index
  220.      *
  221.      * @return int 
  222.      */
  223.     public function getSheetIndex({
  224.         return $this->_sheetIndex;
  225.     }
  226.  
  227.     /**
  228.      * Set sheet index
  229.      *
  230.      * @param    int        $pValue        Sheet index
  231.      * @return PHPExcel_Writer_HTML 
  232.      */
  233.     public function setSheetIndex($pValue 0{
  234.         $this->_sheetIndex = $pValue;
  235.         return $this;
  236.     }
  237.  
  238.     /**
  239.      * Write all sheets (resets sheetIndex to NULL)
  240.      */
  241.     public function writeAllSheets({
  242.         $this->_sheetIndex = null;
  243.     }
  244.  
  245.     /**
  246.      * Generate HTML header
  247.      *
  248.      * @param    boolean        $pIncludeStyles        Include styles?
  249.      * @return    string 
  250.      * @throws Exception
  251.      */
  252.     public function generateHTMLHeader($pIncludeStyles false{
  253.         // PHPExcel object known?
  254.         if (is_null($this->_phpExcel)) {
  255.             throw new Exception('Internal PHPExcel object not set to an instance of an object.');
  256.         }
  257.  
  258.         // Construct HTML
  259.         $html '';
  260.         $html .= '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' "\r\n";
  261.         $html .= '<!-- Generated by PHPExcel - http://www.phpexcel.net -->' "\r\n";
  262.         $html .= '<html>' "\r\n";
  263.         $html .= '  <head>' "\r\n";
  264.         $html .= '    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">' "\r\n";
  265.         $html .= '    <title>' htmlspecialchars($this->_phpExcel->getProperties()->getTitle()) '</title>' "\r\n";
  266.         if ($pIncludeStyles{
  267.             $html .= $this->generateStyles(true);
  268.         }
  269.         $html .= '  </head>' "\r\n";
  270.         $html .= '' "\r\n";
  271.         $html .= '  <body>' "\r\n";
  272.  
  273.         // Return
  274.         return $html;
  275.     }
  276.  
  277.     /**
  278.      * Generate sheet data
  279.      *
  280.      * @return    string 
  281.      * @throws Exception
  282.      */
  283.     public function generateSheetData({
  284.         // PHPExcel object known?
  285.         if (is_null($this->_phpExcel)) {
  286.             throw new Exception('Internal PHPExcel object not set to an instance of an object.');
  287.         }
  288.  
  289.         // Fetch sheets
  290.         $sheets array();
  291.         if (is_null($this->_sheetIndex)) {
  292.             $sheets $this->_phpExcel->getAllSheets();
  293.         else {
  294.             $sheets[$this->_phpExcel->getSheet($this->_sheetIndex);
  295.         }
  296.  
  297.         // Construct HTML
  298.         $html '';
  299.  
  300.         // Loop all sheets
  301.         $sheetId 0;
  302.         foreach ($sheets as $sheet{
  303.             // Get cell collection
  304.             $cellCollection $sheet->getCellCollection();
  305.  
  306.             // Write table header
  307.             $html .= $this->_generateTableHeader($sheet);
  308.  
  309.             // Get worksheet dimension
  310.             $dimension explode(':'$sheet->calculateWorksheetDimension());
  311.             $dimension[0PHPExcel_Cell::coordinateFromString($dimension[0]);
  312.             $dimension[0][0PHPExcel_Cell::columnIndexFromString($dimension[0][0]1;
  313.             $dimension[1PHPExcel_Cell::coordinateFromString($dimension[1]);
  314.             $dimension[1][0PHPExcel_Cell::columnIndexFromString($dimension[1][0]1;
  315.  
  316.             // Loop trough cells
  317.             $rowData null;
  318.             for ($row $dimension[0][1]$row <= $dimension[1][1]++$row{
  319.                 // Start a new row
  320.                 $rowData array();
  321.  
  322.                 // Loop trough columns
  323.                 for ($column $dimension[0][0]$column <= $dimension[1][0]++$column{
  324.                     // Cell exists?
  325.                     if ($sheet->cellExistsByColumnAndRow($column$row)) {
  326.                         $rowData[$column$sheet->getCellByColumnAndRow($column$row);
  327.                     else {
  328.                         $rowData[$column'';
  329.                     }
  330.                 }
  331.  
  332.                 // Write row
  333.                 $html .= $this->_generateRow($sheet$rowData$row 1);
  334.             }
  335.  
  336.             // Write table footer
  337.             $html .= $this->_generateTableFooter();
  338.             
  339.             // Writing PDF?
  340.             if ($this->_isPdf)
  341.             {
  342.                 if (is_null($this->_sheetIndex&& $sheetId $this->_phpExcel->getSheetCount()) {
  343.                     $html .= '<tcpdf method="AddPage" />';
  344.                 }
  345.             }
  346.             
  347.             // Next sheet
  348.             ++$sheetId;
  349.         }
  350.  
  351.         // Return
  352.         return $html;
  353.     }
  354.  
  355.     /**
  356.      * Generate image tag in cell
  357.      *
  358.      * @param    PHPExcel_Worksheet     $pSheet            PHPExcel_Worksheet
  359.      * @param    string                $coordinates    Cell coordinates
  360.      * @return    string 
  361.      * @throws    Exception
  362.      */
  363.     private function _writeImageTagInCell(PHPExcel_Worksheet $pSheet$coordinates{
  364.         // Construct HTML
  365.         $html '';
  366.  
  367.         // Write images
  368.         foreach ($pSheet->getDrawingCollection(as $drawing{
  369.             if ($drawing instanceof PHPExcel_Worksheet_Drawing{
  370.                 if ($drawing->getCoordinates(== $coordinates{
  371.                     $filename $drawing->getPath();
  372.  
  373.                     // Strip off eventual '.'
  374.                     if (substr($filename01== '.'{
  375.                         $filename substr($filename1);
  376.                     }
  377.  
  378.                     // Prepend images root
  379.                     $filename $this->getImagesRoot($filename;
  380.  
  381.                     // Strip off eventual '.'
  382.                     if (substr($filename01== '.' && substr($filename02!= './'{
  383.                         $filename substr($filename1);
  384.                     }
  385.  
  386.                     // Convert UTF8 data to PCDATA
  387.                     $filename htmlspecialchars($filename);
  388.  
  389.                     $html .= "\r\n";
  390.                     $html .= '        <img style="position: relative; left: ' $drawing->getOffsetX('px; top: ' $drawing->getOffsetY('px; width: ' $drawing->getWidth('px; height: ' $drawing->getHeight('px;" src="' $filename '" border="0" width="' $drawing->getWidth('" height="' $drawing->getHeight('" />' "\r\n";
  391.                 }
  392.             }
  393.         }
  394.  
  395.         // Return
  396.         return $html;
  397.     }
  398.  
  399.     /**
  400.      * Generate CSS styles
  401.      *
  402.      * @param    boolean    $generateSurroundingHTML    Generate surrounding HTML tags? (<style> and </style>)
  403.      * @return    string 
  404.      * @throws    Exception
  405.      */
  406.     public function generateStyles($generateSurroundingHTML true{
  407.         // PHPExcel object known?
  408.         if (is_null($this->_phpExcel)) {
  409.             throw new Exception('Internal PHPExcel object not set to an instance of an object.');
  410.         }
  411.         
  412.         // Build CSS
  413.         $css $this->buildCSS($generateSurroundingHTML);
  414.  
  415.         // Construct HTML
  416.         $html '';
  417.  
  418.         // Start styles
  419.         if ($generateSurroundingHTML{
  420.             $html .= '    <style type="text/css">' "\r\n";
  421.             $html .= '      html { ' $this->_assembleCSS($css['html']' }' "\r\n";
  422.         }
  423.         
  424.         // Write all other styles
  425.         foreach ($css as $styleName => $styleDefinition{
  426.             if ($styleName != 'html'{
  427.                 $html .= '      ' $styleName ' { ' $this->_assembleCSS($styleDefinition' }' "\r\n";
  428.             }
  429.         }
  430.  
  431.         // End styles
  432.         if ($generateSurroundingHTML{
  433.             $html .= '    </style>' "\r\n";
  434.         }
  435.  
  436.         // Return
  437.         return $html;
  438.     }
  439.     
  440.     /**
  441.      * Build CSS styles
  442.      *
  443.      * @param    boolean    $generateSurroundingHTML    Generate surrounding HTML style? (html { })
  444.      * @return    array 
  445.      * @throws    Exception
  446.      */
  447.     public function buildCSS($generateSurroundingHTML true{
  448.         // PHPExcel object known?
  449.         if (is_null($this->_phpExcel)) {
  450.             throw new Exception('Internal PHPExcel object not set to an instance of an object.');
  451.         }
  452.         
  453.         // Cached?
  454.         if (!is_null($this->_cssStyles)) {
  455.             return $this->_cssStyles;
  456.         }
  457.  
  458.         // Construct CSS
  459.         $css array();
  460.  
  461.         // Start styles
  462.         if ($generateSurroundingHTML{
  463.             // html { }
  464.             $css['html']['font-family']      'Calibri, Arial, Helvetica, sans-serif';
  465.             $css['html']['font-size']        '11pt';
  466.             $css['html']['background-color''white';
  467.         }
  468.  
  469.  
  470.         // table { }
  471.         $css['table']['border-collapse']  'collapse';
  472.         $css['table']['page-break-after''always';
  473.  
  474.         // .gridlines td { }
  475.         $css['.gridlines td']['border''1px dotted black';
  476.  
  477.         // .b {}
  478.         $css['.b']['text-align''center'// BOOL
  479.  
  480.         // .e {}
  481.         $css['.e']['text-align''center'// ERROR
  482.  
  483.         // .f {}
  484.         $css['.f']['text-align''right'// FORMULA
  485.  
  486.         // .inlineStr {}
  487.         $css['.inlineStr']['text-align''left'// INLINE
  488.  
  489.         // .n {}
  490.         $css['.n']['text-align''right'// NUMERIC
  491.  
  492.         // .s {}
  493.         $css['.s']['text-align''left'// STRING
  494.  
  495.         // Calculate cell style hashes
  496.         foreach ($this->_phpExcel->getCellXfCollection(as $index => $style{
  497.             $css['td.style' $index$this->_createCSSStyle$style );
  498.         }
  499.  
  500.         // Fetch sheets
  501.         $sheets array();
  502.         if (is_null($this->_sheetIndex)) {
  503.             $sheets $this->_phpExcel->getAllSheets();
  504.         else {
  505.             $sheets[$this->_phpExcel->getSheet($this->_sheetIndex);
  506.         }
  507.  
  508.         // Build styles per sheet
  509.         foreach ($sheets as $sheet{
  510.             // Calculate hash code
  511.             $sheetIndex $sheet->getParent()->getIndex($sheet);
  512.  
  513.             // Build styles
  514.             // Calculate column widths
  515.             $sheet->calculateColumnWidths();
  516.  
  517.             // col elements, initialize
  518.             $highestColumnIndex PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn()) 1;
  519.             for ($column 0$column <= $highestColumnIndex++$column{
  520.                 $this->_columnWidths[$sheetIndex][$column42// approximation
  521.                 $css['table.sheet' $sheetIndex ' col.col' $column]['width''42pt';
  522.             }
  523.  
  524.             // col elements, loop through columnDimensions and set width
  525.             foreach ($sheet->getColumnDimensions(as $columnDimension{
  526.                 if (($width PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth()$this->_defaultFontSize)) >= 0{
  527.                     $width PHPExcel_Shared_Drawing::pixelsToPoints($width);
  528.                     $column PHPExcel_Cell::columnIndexFromString($columnDimension->getColumnIndex()) 1;
  529.                     $this->_columnWidths[$sheetIndex][$column$width;
  530.                     $css['table.sheet' $sheetIndex ' col.col' $column]['width'$width 'pt';
  531.                     
  532.                     if ($columnDimension->getVisible(=== false{
  533.                         $css['table.sheet' $sheetIndex ' col.col' $column]['visibility''collapse';
  534.                         $css['table.sheet' $sheetIndex ' col.col' $column]['*display''none'// target IE6+7
  535.                     }
  536.                 }
  537.             }
  538.  
  539.             // Default row height
  540.             $rowDimension $sheet->getDefaultRowDimension();
  541.  
  542.             // table.sheetN tr { }
  543.             $css['table.sheet' $sheetIndex ' tr'array();
  544.  
  545.             $pt_height $rowDimension->getRowHeight();
  546.             $css['table.sheet' $sheetIndex ' tr']['height'$pt_height 'pt';
  547.             if ($rowDimension->getVisible(=== false{
  548.                 $css['table.sheet' $sheetIndex ' tr']['display']    'none';
  549.                 $css['table.sheet' $sheetIndex ' tr']['visibility''hidden';
  550.             }
  551.  
  552.             // Calculate row heights
  553.             foreach ($sheet->getRowDimensions(as $rowDimension{
  554.                 $row $rowDimension->getRowIndex(1;
  555.  
  556.                 // table.sheetN tr.rowYYYYYY { }
  557.                 $css['table.sheet' $sheetIndex ' tr.row' $rowarray();
  558.  
  559.                 $pt_height $rowDimension->getRowHeight();
  560.                 $css['table.sheet' $sheetIndex ' tr.row' $row]['height'$pt_height 'pt';
  561.                 if ($rowDimension->getVisible(=== false{
  562.                     $css['table.sheet' $sheetIndex ' tr.row' $row]['display''none';
  563.                     $css['table.sheet' $sheetIndex ' tr.row' $row]['visibility''hidden';
  564.                 }
  565.             }
  566.         }
  567.  
  568.         // Cache
  569.         if (is_null($this->_cssStyles)) {
  570.             $this->_cssStyles = $css;
  571.         }
  572.         
  573.         // Return
  574.         return $css;
  575.     }
  576.  
  577.     /**
  578.      * Create CSS style
  579.      *
  580.      * @param    PHPExcel_Style         $pStyle            PHPExcel_Style
  581.      * @return    array 
  582.      */
  583.     private function _createCSSStyle(PHPExcel_Style $pStyle{
  584.         // Construct CSS
  585.         $css '';
  586.  
  587.         // Create CSS
  588.         $css array_merge(
  589.             $this->_createCSSStyleAlignment($pStyle->getAlignment())
  590.             $this->_createCSSStyleBorders($pStyle->getBorders())
  591.             $this->_createCSSStyleFont($pStyle->getFont())
  592.             $this->_createCSSStyleFill($pStyle->getFill())
  593.         );
  594.  
  595.         // Return
  596.         return $css;
  597.     }
  598.  
  599.     /**
  600.      * Create CSS style (PHPExcel_Style_Alignment)
  601.      *
  602.      * @param    PHPExcel_Style_Alignment         $pStyle            PHPExcel_Style_Alignment
  603.      * @return    array 
  604.      */
  605.     private function _createCSSStyleAlignment(PHPExcel_Style_Alignment $pStyle{
  606.         // Construct CSS
  607.         $css array();
  608.  
  609.         // Create CSS
  610.         $css['vertical-align'$this->_mapVAlign($pStyle->getVertical());
  611.         if ($textAlign $this->_mapHAlign($pStyle->getHorizontal())) {
  612.             $css['text-align'$textAlign;
  613.         }
  614.  
  615.         // Return
  616.         return $css;
  617.     }
  618.  
  619.     /**
  620.      * Create CSS style (PHPExcel_Style_Font)
  621.      *
  622.      * @param    PHPExcel_Style_Font         $pStyle            PHPExcel_Style_Font
  623.      * @return    array 
  624.      */
  625.     private function _createCSSStyleFont(PHPExcel_Style_Font $pStyle{
  626.         // Construct CSS
  627.         $css array();
  628.  
  629.         // Create CSS
  630.         if ($pStyle->getBold()) {
  631.             $css['font-weight''bold';
  632.         }
  633.         if ($pStyle->getUnderline(!= PHPExcel_Style_Font::UNDERLINE_NONE && $pStyle->getStrikethrough()) {
  634.             $css['text-decoration''underline line-through';
  635.         else if ($pStyle->getUnderline(!= PHPExcel_Style_Font::UNDERLINE_NONE{
  636.             $css['text-decoration''underline';
  637.         else if ($pStyle->getStrikethrough()) {
  638.             $css['text-decoration''line-through';
  639.         }
  640.         if ($pStyle->getItalic()) {
  641.             $css['font-style''italic';
  642.         }
  643.  
  644.         $css['color']        '#' $pStyle->getColor()->getRGB();
  645.         $css['font-family']    '\'' $pStyle->getName('\'';
  646.         $css['font-size']    $pStyle->getSize('pt';
  647.  
  648.         // Return
  649.         return $css;
  650.     }
  651.  
  652.     /**
  653.      * Create CSS style (PHPExcel_Style_Borders)
  654.      *
  655.      * @param    PHPExcel_Style_Borders         $pStyle            PHPExcel_Style_Borders
  656.      * @return    array 
  657.      */
  658.     private function _createCSSStyleBorders(PHPExcel_Style_Borders $pStyle{
  659.         // Construct CSS
  660.         $css array();
  661.  
  662.         // Create CSS
  663.         $css['border-bottom']    $this->_createCSSStyleBorder($pStyle->getBottom());
  664.         $css['border-top']        $this->_createCSSStyleBorder($pStyle->getTop());
  665.         $css['border-left']        $this->_createCSSStyleBorder($pStyle->getLeft());
  666.         $css['border-right']    $this->_createCSSStyleBorder($pStyle->getRight());
  667.  
  668.         // Return
  669.         return $css;
  670.     }
  671.  
  672.     /**
  673.      * Create CSS style (PHPExcel_Style_Border)
  674.      *
  675.      * @param    PHPExcel_Style_Border        $pStyle            PHPExcel_Style_Border
  676.      * @return    string 
  677.      */
  678.     private function _createCSSStyleBorder(PHPExcel_Style_Border $pStyle{
  679.         // Construct HTML
  680.         $css '';
  681.  
  682.         // Create CSS
  683.         $css .= $this->_mapBorderStyle($pStyle->getBorderStyle()) ' #' $pStyle->getColor()->getRGB();
  684.  
  685.         // Return
  686.         return $css;
  687.     }
  688.  
  689.     /**
  690.      * Create CSS style (PHPExcel_Style_Fill)
  691.      *
  692.      * @param    PHPExcel_Style_Fill        $pStyle            PHPExcel_Style_Fill
  693.      * @return    array 
  694.      */
  695.     private function _createCSSStyleFill(PHPExcel_Style_Fill $pStyle{
  696.         // Construct HTML
  697.         $css array();
  698.  
  699.         // Create CSS
  700.         $value $pStyle->getFillType(== PHPExcel_Style_Fill::FILL_NONE ?
  701.             'white' '#' $pStyle->getStartColor()->getRGB();
  702.         $css['background-color'$value;
  703.  
  704.         // Return
  705.         return $css;
  706.     }
  707.  
  708.     /**
  709.      * Generate HTML footer
  710.      */
  711.     public function generateHTMLFooter({
  712.         // Construct HTML
  713.         $html '';
  714.         $html .= '  </body>' "\r\n";
  715.         $html .= '</html>' "\r\n";
  716.  
  717.         // Return
  718.         return $html;
  719.     }
  720.  
  721.     /**
  722.      * Generate table header
  723.      *
  724.      * @param     PHPExcel_Worksheet    $pSheet        The worksheet for the table we are writing
  725.      * @return    string 
  726.      * @throws    Exception
  727.      */
  728.     private function _generateTableHeader($pSheet{
  729.         $sheetIndex $pSheet->getParent()->getIndex($pSheet);
  730.  
  731.         // Construct HTML
  732.         $html '';
  733.         
  734.         if (!$this->_useInlineCss{
  735.             $gridlines $pSheet->getShowGridLines(' gridlines' '';
  736.             $html .= '    <table border="0" cellpadding="0" cellspacing="0" class="sheet' $sheetIndex $gridlines '">' "\r\n";
  737.         else {
  738.             $style = isset($this->_cssStyles['table']?
  739.                 $this->_assembleCSS($this->_cssStyles['table']'';
  740.  
  741.             $html .= '    <table border="0" cellpadding="0" cellspacing="0" style="' $style '">' "\r\n";
  742.         }
  743.  
  744.         // Write <col> elements
  745.         $highestColumnIndex PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn()) 1;
  746.         for ($i 0$i <= $highestColumnIndex++$i{
  747.             if (!$this->_useInlineCss{
  748.                 $html .= '        <col class="col' $i '">' "\r\n";
  749.             else {
  750.                 $style = isset($this->_cssStyles['table.sheet' $sheetIndex ' col.col' $i]?
  751.                     $this->_assembleCSS($this->_cssStyles['table.sheet' $sheetIndex ' col.col' $i]'';
  752.                 $html .= '        <col style="' $style '">' "\r\n";
  753.             }
  754.         }
  755.  
  756.         // Return
  757.         return $html;
  758.     }
  759.  
  760.     /**
  761.      * Generate table footer
  762.      *
  763.      * @throws    Exception
  764.      */
  765.     private function _generateTableFooter({
  766.         // Construct HTML
  767.         $html '';
  768.         $html .= '    </table>' "\r\n";
  769.  
  770.         // Return
  771.         return $html;
  772.     }
  773.  
  774.     /**
  775.      * Generate row
  776.      *
  777.      * @param    PHPExcel_Worksheet     $pSheet            PHPExcel_Worksheet
  778.      * @param    array                $pValues        Array containing cells in a row
  779.      * @param    int                    $pRow            Row number
  780.      * @return    string 
  781.      * @throws    Exception
  782.      */
  783.     private function _generateRow(PHPExcel_Worksheet $pSheet$pValues null$pRow 0{
  784.         if (is_array($pValues)) {
  785.             // Construct HTML
  786.             $html '';
  787.             
  788.             // Sheet index
  789.             $sheetIndex $pSheet->getParent()->getIndex($pSheet);
  790.  
  791.             // Write row start
  792.             if (!$this->_useInlineCss{
  793.                 $html .= '        <tr class="row' $pRow '">' "\r\n";
  794.             else {
  795.                 $style = isset($this->_cssStyles['table.sheet' $sheetIndex ' tr.row' $pRow])
  796.                     ? $this->_assembleCSS($this->_cssStyles['table.sheet' $sheetIndex ' tr.row' $pRow]'';
  797.                     
  798.                 $html .= '        <tr style="' $style '">' "\r\n";
  799.             }
  800.  
  801.             // Write cells
  802.             $colNum 0;
  803.             foreach ($pValues as $cell{
  804.                 if (!$this->_useInlineCss{
  805.                     $cssClass '';
  806.                     $cssClass 'column' $colNum;
  807.                 else {
  808.                     $cssClass array();
  809.                     if (isset($this->_cssStyles['table.sheet' $sheetIndex ' td.column' $colNum])) {
  810.                         $this->_cssStyles['table.sheet' $sheetIndex ' td.column' $colNum];
  811.                     }
  812.                 }
  813.                 $colSpan 1;
  814.                 $rowSpan 1;
  815.                 $writeCell true;    // Write cell
  816.  
  817.                 // initialize
  818.                 $cellData '';
  819.  
  820.                 // PHPExcel_Cell
  821.                 if ($cell instanceof PHPExcel_Cell{
  822.  
  823.                     // Value
  824.                     if ($cell->getValue(instanceof PHPExcel_RichText{
  825.                         // Loop trough rich text elements
  826.                         $elements $cell->getValue()->getRichTextElements();
  827.                         foreach ($elements as $element{
  828.                             // Rich text start?
  829.                             if ($element instanceof PHPExcel_RichText_Run{
  830.                                 $cellData .= '<span style="' $this->_assembleCSS($this->_createCSSStyleFont($element->getFont())) '">';
  831.  
  832.                                 if ($element->getFont()->getSuperScript()) {
  833.                                     $cellData .= '<sup>';
  834.                                 else if ($element->getFont()->getSubScript()) {
  835.                                     $cellData .= '<sub>';
  836.                                 }
  837.                             }
  838.  
  839.                             // Convert UTF8 data to PCDATA
  840.                             $cellText $element->getText();
  841.                             $cellData .= htmlspecialchars($cellText);
  842.  
  843.                             if ($element instanceof PHPExcel_RichText_Run{
  844.                                 if ($element->getFont()->getSuperScript()) {
  845.                                     $cellData .= '</sup>';
  846.                                 else if ($element->getFont()->getSubScript()) {
  847.                                     $cellData .= '</sub>';
  848.                                 }
  849.  
  850.                                 $cellData .= '</span>';
  851.                             }
  852.                         }
  853.                     else {
  854.                         if ($this->_preCalculateFormulas{
  855.                             $cellData PHPExcel_Style_NumberFormat::toFormattedString(
  856.                                 $cell->getCalculatedValue(),
  857.                                 $pSheet->getParent()->getCellXfByIndex$cell->getXfIndex() )->getNumberFormat()->getFormatCode()
  858.                             );
  859.                         else {
  860.                             $cellData PHPExcel_Style_NumberFormat::ToFormattedString(
  861.                                 $cell->getValue(),
  862.                                 $pSheet->getParent()->getCellXfByIndex$cell->getXfIndex() )->getNumberFormat()->getFormatCode()
  863.                             );
  864.                         }
  865.  
  866.                         // Convert UTF8 data to PCDATA
  867.                         $cellData htmlspecialchars($cellData);
  868.                     }
  869.  
  870.                     // replace leading spaces on each line with &nbsp;
  871.                     $cellData $this->_convertNbsp($cellData);
  872.  
  873.                     // convert newline "\n" to '<br>'
  874.                     $cellData str_replace("\n"'<br/>'$cellData);
  875.  
  876.                     // Check value
  877.                     if ($cellData == ''{
  878.                         $cellData '&nbsp;';
  879.                     }
  880.  
  881.                     // Extend CSS class?
  882.                     if (!$this->_useInlineCss{
  883.                         $cssClass .= ' style' $cell->getXfIndex();
  884.                         $cssClass .= ' ' $cell->getDataType();
  885.                     else {
  886.                         if (isset($this->_cssStyles['td.style' $cell->getXfIndex()])) {
  887.                             $cssClass array_merge($cssClass$this->_cssStyles['td.style' $cell->getXfIndex()]);
  888.                         }
  889.  
  890.                         // General horizontal alignment: Actual horizontal alignment depends on dataType
  891.                         $sharedStyle $pSheet->getParent()->getCellXfByIndex$cell->getXfIndex() );
  892.                         if ($sharedStyle->getAlignment()->getHorizontal(== PHPExcel_Style_Alignment::HORIZONTAL_GENERAL
  893.                             && isset($this->_cssStyles['.' $cell->getDataType()]['text-align']))
  894.                         {
  895.                             $cssClass['text-align'$this->_cssStyles['.' $cell->getDataType()]['text-align'];
  896.                         }
  897.                     }
  898.                 else {
  899.                     $cell new PHPExcel_Cell(
  900.                         PHPExcel_Cell::stringFromColumnIndex($colNum),
  901.                         ($pRow 1),
  902.                         '',
  903.                         PHPExcel_Cell_DataType::TYPE_NULL,
  904.                         $pSheet
  905.                     );
  906.                 }
  907.  
  908.                 // Hyperlink?
  909.                 if ($cell->hasHyperlink(&& !$cell->getHyperlink()->isInternal()) {
  910.                     $cellData '<a href="' htmlspecialchars($cell->getHyperlink()->getUrl()) '" title="' htmlspecialchars($cell->getHyperlink()->getTooltip()) '">' $cellData '</a>';
  911.                 }
  912.  
  913.                 // Column/rowspan
  914.                 foreach ($pSheet->getMergeCells(as $cells{
  915.                     if ($cell->isInRange($cells)) {
  916.                         list($firstPHPExcel_Cell::splitRange($cells);
  917.  
  918.                         if ($first[0== $cell->getCoordinate()) {
  919.                             list($colSpan$rowSpanPHPExcel_Cell::rangeDimension($cells);
  920.                         else {
  921.                             $writeCell false;
  922.                         }
  923.  
  924.                         break;
  925.                     }
  926.                 }
  927.  
  928.                 // Write
  929.                 if ($writeCell{
  930.                     // Column start
  931.                     $html .= '          <td';
  932.                         if (!$this->_useInlineCss{
  933.                             $html .= ' class="' $cssClass '"';
  934.                         else {
  935.                             //** Necessary redundant code for the sake of PHPExcel_Writer_PDF **
  936.                             // We must explicitly write the width of the <td> element because TCPDF
  937.                             // does not recognize e.g. <col style="width:42pt">
  938.                             $width 0;
  939.                             $columnIndex PHPExcel_Cell::columnIndexFromString($cell->getColumn()) 1;
  940.                             for ($i $columnIndex$i $columnIndex $colSpan++$i{
  941.                                 if (isset($this->_columnWidths[$sheetIndex][$i])) {
  942.                                     $width += $this->_columnWidths[$sheetIndex][$i];
  943.                                 }
  944.                             }
  945.                             $cssClass['width'$width 'pt';
  946.                             
  947.                             // We must also explicitly write the height of the <td> element because TCPDF
  948.                             // does not recognize e.g. <tr style="height:50pt">
  949.                             if (isset($this->_cssStyles['table.sheet' $sheetIndex ' tr.row' $pRow]['height'])) {
  950.                                 $height $this->_cssStyles['table.sheet' $sheetIndex ' tr.row' $pRow]['height'];
  951.                                 $cssClass['height'$height;
  952.                             }
  953.                             //** end of redundant code **
  954.                             
  955.                             $html .= ' style="' $this->_assembleCSS($cssClass'"';
  956.                         }
  957.                         if ($colSpan 1{
  958.                             $html .= ' colspan="' $colSpan '"';
  959.                         }
  960.                         if ($rowSpan 1{
  961.                             $html .= ' rowspan="' $rowSpan '"';
  962.                         }
  963.                     $html .= '>';
  964.  
  965.                     // Image?
  966.                     $html .= $this->_writeImageTagInCell($pSheet$cell->getCoordinate());
  967.  
  968.                     // Cell data
  969.                     $html .= $cellData;
  970.                     
  971.                     // Column end
  972.                     $html .= '</td>' "\r\n";
  973.                 }
  974.  
  975.                 // Next column
  976.                 ++$colNum;
  977.             }
  978.  
  979.             // Write row end
  980.             $html .= '        </tr>' "\r\n";
  981.  
  982.             // Return
  983.             return $html;
  984.         else {
  985.             throw new Exception("Invalid parameters passed.");
  986.         }
  987.     }
  988.  
  989.     /**
  990.      * Takes array where of CSS properties / values and converts to CSS string
  991.      *
  992.      * @param array 
  993.      * @return string 
  994.      */
  995.     private function _assembleCSS($pValue array())
  996.     {
  997.         $pairs array();
  998.         foreach ($pValue as $property => $value{
  999.             $pairs[$property ':' $value;
  1000.         }
  1001.         $string implode('; '$pairs);
  1002.  
  1003.         return $string;
  1004.     }
  1005.  
  1006.     /**
  1007.      * Get Pre-Calculate Formulas
  1008.      *
  1009.      * @return boolean 
  1010.      */
  1011.     public function getPreCalculateFormulas({
  1012.         return $this->_preCalculateFormulas;
  1013.     }
  1014.  
  1015.     /**
  1016.      * Set Pre-Calculate Formulas
  1017.      *
  1018.      * @param boolean $pValue    Pre-Calculate Formulas?
  1019.      * @return PHPExcel_Writer_HTML 
  1020.      */
  1021.     public function setPreCalculateFormulas($pValue true{
  1022.         $this->_preCalculateFormulas = $pValue;
  1023.         return $this;
  1024.     }
  1025.  
  1026.     /**
  1027.      * Get images root
  1028.      *
  1029.      * @return string 
  1030.      */
  1031.     public function getImagesRoot({
  1032.         return $this->_imagesRoot;
  1033.     }
  1034.  
  1035.     /**
  1036.      * Set images root
  1037.      *
  1038.      * @param string $pValue 
  1039.      * @return PHPExcel_Writer_HTML 
  1040.      */
  1041.     public function setImagesRoot($pValue '.'{
  1042.         $this->_imagesRoot = $pValue;
  1043.         return $this;
  1044.     }
  1045.     
  1046.     /**
  1047.      * Get use inline CSS?
  1048.      *
  1049.      * @return boolean 
  1050.      */
  1051.     public function getUseInlineCss({
  1052.         return $this->_useInlineCss;
  1053.     }
  1054.  
  1055.     /**
  1056.      * Set use inline CSS?
  1057.      *
  1058.      * @param boolean $pValue 
  1059.      * @return PHPExcel_Writer_HTML 
  1060.      */
  1061.     public function setUseInlineCss($pValue false{
  1062.         $this->_useInlineCss = $pValue;
  1063.         return $this;
  1064.     }
  1065.  
  1066.     /**
  1067.      * Converts a string so that spaces occuring at beginning of each new line are replaced by &nbsp;
  1068.      * Example: "  Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world"
  1069.      *
  1070.      * @param string $pValue 
  1071.      * @return string 
  1072.      */
  1073.     private function _convertNbsp($pValue '')
  1074.     {
  1075.         $explodes explode("\n"$pValue);
  1076.         foreach ($explodes as $explode{
  1077.             $matches array();
  1078.             if (preg_match('/^( )+/'$explode$matches)) {
  1079.                 $explode str_repeat('&nbsp;'strlen($matches[0])) substr($explodestrlen($matches[0]));
  1080.             }
  1081.             $implodes[$explode;
  1082.         }
  1083.  
  1084.         $string implode("\n"$implodes);
  1085.         return $string;
  1086.     }
  1087.  
  1088. }

Documentation generated on Mon, 10 Aug 2009 08:06:02 +0200 by phpDocumentor 1.4.1