source: sourcecode/application/libraries/PHPExcel/Writer/Excel2007.php @ 1

Last change on this file since 1 was 1, checked in by dungnv, 11 years ago
File size: 18.5 KB
Line 
1<?php
2/**
3 * PHPExcel
4 *
5 * Copyright (c) 2006 - 2014 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_Excel2007
23 * @copyright  Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
24 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
25 * @version    1.8.0, 2014-03-02
26 */
27
28
29/**
30 * PHPExcel_Writer_Excel2007
31 *
32 * @category   PHPExcel
33 * @package    PHPExcel_Writer_2007
34 * @copyright  Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
35 */
36class PHPExcel_Writer_Excel2007 extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter
37{
38        /**
39         * Pre-calculate formulas
40         * Forces PHPExcel to recalculate all formulae in a workbook when saving, so that the pre-calculated values are
41         *    immediately available to MS Excel or other office spreadsheet viewer when opening the file
42         *
43     * Overrides the default TRUE for this specific writer for performance reasons
44     *
45         * @var boolean
46         */
47        protected $_preCalculateFormulas = FALSE;
48
49        /**
50         * Office2003 compatibility
51         *
52         * @var boolean
53         */
54        private $_office2003compatibility = false;
55
56        /**
57         * Private writer parts
58         *
59         * @var PHPExcel_Writer_Excel2007_WriterPart[]
60         */
61        private $_writerParts   = array();
62
63        /**
64         * Private PHPExcel
65         *
66         * @var PHPExcel
67         */
68        private $_spreadSheet;
69
70        /**
71         * Private string table
72         *
73         * @var string[]
74         */
75        private $_stringTable   = array();
76
77        /**
78         * Private unique PHPExcel_Style_Conditional HashTable
79         *
80         * @var PHPExcel_HashTable
81         */
82        private $_stylesConditionalHashTable;
83
84        /**
85         * Private unique PHPExcel_Style HashTable
86         *
87         * @var PHPExcel_HashTable
88         */
89        private $_styleHashTable;
90
91        /**
92         * Private unique PHPExcel_Style_Fill HashTable
93         *
94         * @var PHPExcel_HashTable
95         */
96        private $_fillHashTable;
97
98        /**
99         * Private unique PHPExcel_Style_Font HashTable
100         *
101         * @var PHPExcel_HashTable
102         */
103        private $_fontHashTable;
104
105        /**
106         * Private unique PHPExcel_Style_Borders HashTable
107         *
108         * @var PHPExcel_HashTable
109         */
110        private $_bordersHashTable ;
111
112        /**
113         * Private unique PHPExcel_Style_NumberFormat HashTable
114         *
115         * @var PHPExcel_HashTable
116         */
117        private $_numFmtHashTable;
118
119        /**
120         * Private unique PHPExcel_Worksheet_BaseDrawing HashTable
121         *
122         * @var PHPExcel_HashTable
123         */
124        private $_drawingHashTable;
125
126    /**
127     * Create a new PHPExcel_Writer_Excel2007
128     *
129         * @param       PHPExcel        $pPHPExcel
130     */
131    public function __construct(PHPExcel $pPHPExcel = null)
132    {
133        // Assign PHPExcel
134                $this->setPHPExcel($pPHPExcel);
135
136        $writerPartsArray = array(      'stringtable'   => 'PHPExcel_Writer_Excel2007_StringTable',
137                                                                        'contenttypes'  => 'PHPExcel_Writer_Excel2007_ContentTypes',
138                                                                        'docprops'              => 'PHPExcel_Writer_Excel2007_DocProps',
139                                                                        'rels'                  => 'PHPExcel_Writer_Excel2007_Rels',
140                                                                        'theme'                 => 'PHPExcel_Writer_Excel2007_Theme',
141                                                                        'style'                 => 'PHPExcel_Writer_Excel2007_Style',
142                                                                        'workbook'              => 'PHPExcel_Writer_Excel2007_Workbook',
143                                                                        'worksheet'     => 'PHPExcel_Writer_Excel2007_Worksheet',
144                                                                        'drawing'               => 'PHPExcel_Writer_Excel2007_Drawing',
145                                                                        'comments'              => 'PHPExcel_Writer_Excel2007_Comments',
146                                                                        'chart'                 => 'PHPExcel_Writer_Excel2007_Chart',
147                                                                        'relsvba'               => 'PHPExcel_Writer_Excel2007_RelsVBA',
148                                                                        'relsribbonobjects' => 'PHPExcel_Writer_Excel2007_RelsRibbon'
149                                                                 );
150
151        //      Initialise writer parts
152                //              and Assign their parent IWriters
153                foreach ($writerPartsArray as $writer => $class) {
154                        $this->_writerParts[$writer] = new $class($this);
155                }
156
157        $hashTablesArray = array( '_stylesConditionalHashTable',        '_fillHashTable',               '_fontHashTable',
158                                                                  '_bordersHashTable',                          '_numFmtHashTable',             '_drawingHashTable',
159                                  '_styleHashTable'
160                                                            );
161
162                // Set HashTable variables
163                foreach ($hashTablesArray as $tableName) {
164                        $this->$tableName       = new PHPExcel_HashTable();
165                }
166    }
167
168        /**
169         * Get writer part
170         *
171         * @param       string  $pPartName              Writer part name
172         * @return      PHPExcel_Writer_Excel2007_WriterPart
173         */
174        public function getWriterPart($pPartName = '') {
175                if ($pPartName != '' && isset($this->_writerParts[strtolower($pPartName)])) {
176                        return $this->_writerParts[strtolower($pPartName)];
177                } else {
178                        return null;
179                }
180        }
181
182        /**
183         * Save PHPExcel to file
184         *
185         * @param       string          $pFilename
186         * @throws      PHPExcel_Writer_Exception
187         */
188        public function save($pFilename = null)
189        {
190                if ($this->_spreadSheet !== NULL) {
191                        // garbage collect
192                        $this->_spreadSheet->garbageCollect();
193
194                        // If $pFilename is php://output or php://stdout, make it a temporary file...
195                        $originalFilename = $pFilename;
196                        if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') {
197                                $pFilename = @tempnam(PHPExcel_Shared_File::sys_get_temp_dir(), 'phpxltmp');
198                                if ($pFilename == '') {
199                                        $pFilename = $originalFilename;
200                                }
201                        }
202
203                        $saveDebugLog = PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->getWriteDebugLog();
204                        PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog(FALSE);
205                        $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType();
206                        PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
207
208                        // Create string lookup table
209                        $this->_stringTable = array();
210                        for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
211                                $this->_stringTable = $this->getWriterPart('StringTable')->createStringTable($this->_spreadSheet->getSheet($i), $this->_stringTable);
212                        }
213
214                        // Create styles dictionaries
215                        $this->_styleHashTable->addFromSource(              $this->getWriterPart('Style')->allStyles($this->_spreadSheet)                       );
216                        $this->_stylesConditionalHashTable->addFromSource(      $this->getWriterPart('Style')->allConditionalStyles($this->_spreadSheet)                        );
217                        $this->_fillHashTable->addFromSource(                           $this->getWriterPart('Style')->allFills($this->_spreadSheet)                    );
218                        $this->_fontHashTable->addFromSource(                           $this->getWriterPart('Style')->allFonts($this->_spreadSheet)                    );
219                        $this->_bordersHashTable->addFromSource(                        $this->getWriterPart('Style')->allBorders($this->_spreadSheet)                  );
220                        $this->_numFmtHashTable->addFromSource(                         $this->getWriterPart('Style')->allNumberFormats($this->_spreadSheet)    );
221
222                        // Create drawing dictionary
223                        $this->_drawingHashTable->addFromSource(                        $this->getWriterPart('Drawing')->allDrawings($this->_spreadSheet)               );
224
225                        // Create new ZIP file and open it for writing
226                        $zipClass = PHPExcel_Settings::getZipClass();
227                        $objZip = new $zipClass();
228
229                        //      Retrieve OVERWRITE and CREATE constants from the instantiated zip class
230                        //      This method of accessing constant values from a dynamic class should work with all appropriate versions of PHP
231                        $ro = new ReflectionObject($objZip);
232                        $zipOverWrite = $ro->getConstant('OVERWRITE');
233                        $zipCreate = $ro->getConstant('CREATE');
234
235                        if (file_exists($pFilename)) {
236                                unlink($pFilename);
237                        }
238                        // Try opening the ZIP file
239                        if ($objZip->open($pFilename, $zipOverWrite) !== true) {
240                                if ($objZip->open($pFilename, $zipCreate) !== true) {
241                                        throw new PHPExcel_Writer_Exception("Could not open " . $pFilename . " for writing.");
242                                }
243                        }
244
245                        // Add [Content_Types].xml to ZIP file
246                        $objZip->addFromString('[Content_Types].xml',                   $this->getWriterPart('ContentTypes')->writeContentTypes($this->_spreadSheet, $this->_includeCharts));
247
248                        //if hasMacros, add the vbaProject.bin file, Certificate file(if exists)
249                        if($this->_spreadSheet->hasMacros()){
250                                $macrosCode=$this->_spreadSheet->getMacrosCode();
251                                if(!is_null($macrosCode)){// we have the code ?
252                                        $objZip->addFromString('xl/vbaProject.bin', $macrosCode);//allways in 'xl', allways named vbaProject.bin
253                                        if($this->_spreadSheet->hasMacrosCertificate()){//signed macros ?
254                                                // Yes : add the certificate file and the related rels file
255                                                $objZip->addFromString('xl/vbaProjectSignature.bin', $this->_spreadSheet->getMacrosCertificate());
256                                                $objZip->addFromString('xl/_rels/vbaProject.bin.rels',
257                                                        $this->getWriterPart('RelsVBA')->writeVBARelationships($this->_spreadSheet));
258                                        }
259                                }
260                        }
261                        //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels)
262                        if($this->_spreadSheet->hasRibbon()){
263                                $tmpRibbonTarget=$this->_spreadSheet->getRibbonXMLData('target');
264                                $objZip->addFromString($tmpRibbonTarget, $this->_spreadSheet->getRibbonXMLData('data'));
265                                if($this->_spreadSheet->hasRibbonBinObjects()){
266                                        $tmpRootPath=dirname($tmpRibbonTarget).'/';
267                                        $ribbonBinObjects=$this->_spreadSheet->getRibbonBinObjects('data');//the files to write
268                                        foreach($ribbonBinObjects as $aPath=>$aContent){
269                                                $objZip->addFromString($tmpRootPath.$aPath, $aContent);
270                                        }
271                                        //the rels for files
272                                        $objZip->addFromString($tmpRootPath.'_rels/'.basename($tmpRibbonTarget).'.rels',
273                                                $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->_spreadSheet));
274                                }
275                        }
276                       
277                        // Add relationships to ZIP file
278                        $objZip->addFromString('_rels/.rels',                                   $this->getWriterPart('Rels')->writeRelationships($this->_spreadSheet));
279                        $objZip->addFromString('xl/_rels/workbook.xml.rels',    $this->getWriterPart('Rels')->writeWorkbookRelationships($this->_spreadSheet));
280
281                        // Add document properties to ZIP file
282                        $objZip->addFromString('docProps/app.xml',                              $this->getWriterPart('DocProps')->writeDocPropsApp($this->_spreadSheet));
283                        $objZip->addFromString('docProps/core.xml',                     $this->getWriterPart('DocProps')->writeDocPropsCore($this->_spreadSheet));
284                        $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->_spreadSheet);
285                        if ($customPropertiesPart !== NULL) {
286                                $objZip->addFromString('docProps/custom.xml',           $customPropertiesPart);
287                        }
288
289                        // Add theme to ZIP file
290                        $objZip->addFromString('xl/theme/theme1.xml',                   $this->getWriterPart('Theme')->writeTheme($this->_spreadSheet));
291
292                        // Add string table to ZIP file
293                        $objZip->addFromString('xl/sharedStrings.xml',                  $this->getWriterPart('StringTable')->writeStringTable($this->_stringTable));
294
295                        // Add styles to ZIP file
296                        $objZip->addFromString('xl/styles.xml',                                 $this->getWriterPart('Style')->writeStyles($this->_spreadSheet));
297
298                        // Add workbook to ZIP file
299                        $objZip->addFromString('xl/workbook.xml',                               $this->getWriterPart('Workbook')->writeWorkbook($this->_spreadSheet, $this->_preCalculateFormulas));
300
301                        $chartCount = 0;
302                        // Add worksheets
303                        for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
304                                $objZip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->_spreadSheet->getSheet($i), $this->_stringTable, $this->_includeCharts));
305                                if ($this->_includeCharts) {
306                                        $charts = $this->_spreadSheet->getSheet($i)->getChartCollection();
307                                        if (count($charts) > 0) {
308                                                foreach($charts as $chart) {
309                                                        $objZip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart));
310                                                        $chartCount++;
311                                                }
312                                        }
313                                }
314                        }
315
316                        $chartRef1 = $chartRef2 = 0;
317                        // Add worksheet relationships (drawings, ...)
318                        for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) {
319
320                                // Add relationships
321                                $objZip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels',    $this->getWriterPart('Rels')->writeWorksheetRelationships($this->_spreadSheet->getSheet($i), ($i + 1), $this->_includeCharts));
322
323                                $drawings = $this->_spreadSheet->getSheet($i)->getDrawingCollection();
324                                $drawingCount = count($drawings);
325                                if ($this->_includeCharts) {
326                                        $chartCount = $this->_spreadSheet->getSheet($i)->getChartCount();
327                                }
328
329                                // Add drawing and image relationship parts
330                                if (($drawingCount > 0) || ($chartCount > 0)) {
331                                        // Drawing relationships
332                                        $objZip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->_spreadSheet->getSheet($i),$chartRef1, $this->_includeCharts));
333
334                                        // Drawings
335                                        $objZip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->_spreadSheet->getSheet($i),$chartRef2,$this->_includeCharts));
336                                }
337
338                                // Add comment relationship parts
339                                if (count($this->_spreadSheet->getSheet($i)->getComments()) > 0) {
340                                        // VML Comments
341                                        $objZip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->_spreadSheet->getSheet($i)));
342
343                                        // Comments
344                                        $objZip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->_spreadSheet->getSheet($i)));
345                                }
346
347                                // Add header/footer relationship parts
348                                if (count($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
349                                        // VML Drawings
350                                        $objZip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->_spreadSheet->getSheet($i)));
351
352                                        // VML Drawing relationships
353                                        $objZip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->_spreadSheet->getSheet($i)));
354
355                                        // Media
356                                        foreach ($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
357                                                $objZip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
358                                        }
359                                }
360                        }
361
362                        // Add media
363                        for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
364                                if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) {
365                                        $imageContents = null;
366                                        $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
367                                        if (strpos($imagePath, 'zip://') !== false) {
368                                                $imagePath = substr($imagePath, 6);
369                                                $imagePathSplitted = explode('#', $imagePath);
370
371                                                $imageZip = new ZipArchive();
372                                                $imageZip->open($imagePathSplitted[0]);
373                                                $imageContents = $imageZip->getFromName($imagePathSplitted[1]);
374                                                $imageZip->close();
375                                                unset($imageZip);
376                                        } else {
377                                                $imageContents = file_get_contents($imagePath);
378                                        }
379
380                                        $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
381                                } else if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) {
382                                        ob_start();
383                                        call_user_func(
384                                                $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(),
385                                                $this->getDrawingHashTable()->getByIndex($i)->getImageResource()
386                                        );
387                                        $imageContents = ob_get_contents();
388                                        ob_end_clean();
389
390                                        $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
391                                }
392                        }
393
394                        PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType);
395                        PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
396
397                        // Close file
398                        if ($objZip->close() === false) {
399                                throw new PHPExcel_Writer_Exception("Could not close zip file $pFilename.");
400                        }
401
402                        // If a temporary file was used, copy it to the correct file stream
403                        if ($originalFilename != $pFilename) {
404                                if (copy($pFilename, $originalFilename) === false) {
405                                        throw new PHPExcel_Writer_Exception("Could not copy temporary zip file $pFilename to $originalFilename.");
406                                }
407                                @unlink($pFilename);
408                        }
409                } else {
410                        throw new PHPExcel_Writer_Exception("PHPExcel object unassigned.");
411                }
412        }
413
414        /**
415         * Get PHPExcel object
416         *
417         * @return PHPExcel
418         * @throws PHPExcel_Writer_Exception
419         */
420        public function getPHPExcel() {
421                if ($this->_spreadSheet !== null) {
422                        return $this->_spreadSheet;
423                } else {
424                        throw new PHPExcel_Writer_Exception("No PHPExcel assigned.");
425                }
426        }
427
428        /**
429         * Set PHPExcel object
430         *
431         * @param       PHPExcel        $pPHPExcel      PHPExcel object
432         * @throws      PHPExcel_Writer_Exception
433         * @return PHPExcel_Writer_Excel2007
434         */
435        public function setPHPExcel(PHPExcel $pPHPExcel = null) {
436                $this->_spreadSheet = $pPHPExcel;
437                return $this;
438        }
439
440    /**
441     * Get string table
442     *
443     * @return string[]
444     */
445    public function getStringTable() {
446        return $this->_stringTable;
447    }
448
449    /**
450     * Get PHPExcel_Style HashTable
451     *
452     * @return PHPExcel_HashTable
453     */
454    public function getStyleHashTable() {
455        return $this->_styleHashTable;
456    }
457
458    /**
459     * Get PHPExcel_Style_Conditional HashTable
460     *
461     * @return PHPExcel_HashTable
462     */
463    public function getStylesConditionalHashTable() {
464        return $this->_stylesConditionalHashTable;
465    }
466
467    /**
468     * Get PHPExcel_Style_Fill HashTable
469     *
470     * @return PHPExcel_HashTable
471     */
472    public function getFillHashTable() {
473        return $this->_fillHashTable;
474    }
475
476    /**
477     * Get PHPExcel_Style_Font HashTable
478     *
479     * @return PHPExcel_HashTable
480     */
481    public function getFontHashTable() {
482        return $this->_fontHashTable;
483    }
484
485    /**
486     * Get PHPExcel_Style_Borders HashTable
487     *
488     * @return PHPExcel_HashTable
489     */
490    public function getBordersHashTable() {
491        return $this->_bordersHashTable;
492    }
493
494    /**
495     * Get PHPExcel_Style_NumberFormat HashTable
496     *
497     * @return PHPExcel_HashTable
498     */
499    public function getNumFmtHashTable() {
500        return $this->_numFmtHashTable;
501    }
502
503    /**
504     * Get PHPExcel_Worksheet_BaseDrawing HashTable
505     *
506     * @return PHPExcel_HashTable
507     */
508    public function getDrawingHashTable() {
509        return $this->_drawingHashTable;
510    }
511
512    /**
513     * Get Office2003 compatibility
514     *
515     * @return boolean
516     */
517    public function getOffice2003Compatibility() {
518        return $this->_office2003compatibility;
519    }
520
521    /**
522     * Set Office2003 compatibility
523     *
524     * @param boolean $pValue   Office2003 compatibility?
525     * @return PHPExcel_Writer_Excel2007
526     */
527    public function setOffice2003Compatibility($pValue = false) {
528        $this->_office2003compatibility = $pValue;
529        return $this;
530    }
531
532}
Note: See TracBrowser for help on using the repository browser.