/** * Save PHPExcel to file * * @param string $pFilename * @throws PHPExcel_Writer_Exception */ public function save($pFilename = null) { if ($this->_spreadSheet !== NULL) { // garbage collect $this->_spreadSheet->garbageCollect(); // If $pFilename is php://output or php://stdout, make it a temporary file... $originalFilename = $pFilename; if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') { $pFilename = @tempnam(PHPExcel_Shared_File::sys_get_temp_dir(), 'phpxltmp'); if ($pFilename == '') { $pFilename = $originalFilename; } } $saveDebugLog = PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->getWriteDebugLog(); PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog(FALSE); $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType(); PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL); // Create string lookup table $this->_stringTable = array(); for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) { $this->_stringTable = $this->getWriterPart('StringTable')->createStringTable($this->_spreadSheet->getSheet($i), $this->_stringTable); } // Create styles dictionaries $this->_styleHashTable->addFromSource($this->getWriterPart('Style')->allStyles($this->_spreadSheet)); $this->_stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->_spreadSheet)); $this->_fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->_spreadSheet)); $this->_fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->_spreadSheet)); $this->_bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->_spreadSheet)); $this->_numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->_spreadSheet)); // Create drawing dictionary $this->_drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->_spreadSheet)); // Create new ZIP file and open it for writing $zipClass = PHPExcel_Settings::getZipClass(); $objZip = new $zipClass(); // Retrieve OVERWRITE and CREATE constants from the instantiated zip class // This method of accessing constant values from a dynamic class should work with all appropriate versions of PHP $ro = new ReflectionObject($objZip); $zipOverWrite = $ro->getConstant('OVERWRITE'); $zipCreate = $ro->getConstant('CREATE'); if (file_exists($pFilename)) { unlink($pFilename); } // Try opening the ZIP file if ($objZip->open($pFilename, $zipOverWrite) !== true) { if ($objZip->open($pFilename, $zipCreate) !== true) { throw new PHPExcel_Writer_Exception("Could not open " . $pFilename . " for writing."); } } // Add [Content_Types].xml to ZIP file $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->_spreadSheet, $this->_includeCharts)); //if hasMacros, add the vbaProject.bin file, Certificate file(if exists) if ($this->_spreadSheet->hasMacros()) { $macrosCode = $this->_spreadSheet->getMacrosCode(); if (!is_null($macrosCode)) { // we have the code ? $objZip->addFromString('xl/vbaProject.bin', $macrosCode); //allways in 'xl', allways named vbaProject.bin if ($this->_spreadSheet->hasMacrosCertificate()) { //signed macros ? // Yes : add the certificate file and the related rels file $objZip->addFromString('xl/vbaProjectSignature.bin', $this->_spreadSheet->getMacrosCertificate()); $objZip->addFromString('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->_spreadSheet)); } } } //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels) if ($this->_spreadSheet->hasRibbon()) { $tmpRibbonTarget = $this->_spreadSheet->getRibbonXMLData('target'); $objZip->addFromString($tmpRibbonTarget, $this->_spreadSheet->getRibbonXMLData('data')); if ($this->_spreadSheet->hasRibbonBinObjects()) { $tmpRootPath = dirname($tmpRibbonTarget) . '/'; $ribbonBinObjects = $this->_spreadSheet->getRibbonBinObjects('data'); //the files to write foreach ($ribbonBinObjects as $aPath => $aContent) { $objZip->addFromString($tmpRootPath . $aPath, $aContent); } //the rels for files $objZip->addFromString($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->_spreadSheet)); } } // Add relationships to ZIP file $objZip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->_spreadSheet)); $objZip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->_spreadSheet)); // Add document properties to ZIP file $objZip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->_spreadSheet)); $objZip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->_spreadSheet)); $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->_spreadSheet); if ($customPropertiesPart !== NULL) { $objZip->addFromString('docProps/custom.xml', $customPropertiesPart); } // Add theme to ZIP file $objZip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->_spreadSheet)); // Add string table to ZIP file $objZip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->_stringTable)); // Add styles to ZIP file $objZip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->_spreadSheet)); // Add workbook to ZIP file $objZip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->_spreadSheet, $this->_preCalculateFormulas)); $chartCount = 0; // Add worksheets for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) { $objZip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->_spreadSheet->getSheet($i), $this->_stringTable, $this->_includeCharts)); if ($this->_includeCharts) { $charts = $this->_spreadSheet->getSheet($i)->getChartCollection(); if (count($charts) > 0) { foreach ($charts as $chart) { $objZip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart)); $chartCount++; } } } } $chartRef1 = $chartRef2 = 0; // Add worksheet relationships (drawings, ...) for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) { // Add relationships $objZip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->_spreadSheet->getSheet($i), $i + 1, $this->_includeCharts)); $drawings = $this->_spreadSheet->getSheet($i)->getDrawingCollection(); $drawingCount = count($drawings); if ($this->_includeCharts) { $chartCount = $this->_spreadSheet->getSheet($i)->getChartCount(); } // Add drawing and image relationship parts if ($drawingCount > 0 || $chartCount > 0) { // Drawing relationships $objZip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->_spreadSheet->getSheet($i), $chartRef1, $this->_includeCharts)); // Drawings $objZip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->_spreadSheet->getSheet($i), $chartRef2, $this->_includeCharts)); } // Add comment relationship parts if (count($this->_spreadSheet->getSheet($i)->getComments()) > 0) { // VML Comments $objZip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->_spreadSheet->getSheet($i))); // Comments $objZip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->_spreadSheet->getSheet($i))); } // Add header/footer relationship parts if (count($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { // VML Drawings $objZip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->_spreadSheet->getSheet($i))); // VML Drawing relationships $objZip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->_spreadSheet->getSheet($i))); // Media foreach ($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { $objZip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath())); } } } // Add media for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) { if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) { $imageContents = null; $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath(); if (strpos($imagePath, 'zip://') !== false) { $imagePath = substr($imagePath, 6); $imagePathSplitted = explode('#', $imagePath); $imageZip = new ZipArchive(); $imageZip->open($imagePathSplitted[0]); $imageContents = $imageZip->getFromName($imagePathSplitted[1]); $imageZip->close(); unset($imageZip); } else { $imageContents = file_get_contents($imagePath); } $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); } else { if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) { ob_start(); call_user_func($this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(), $this->getDrawingHashTable()->getByIndex($i)->getImageResource()); $imageContents = ob_get_contents(); ob_end_clean(); $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); } } } PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType); PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); // Close file if ($objZip->close() === false) { throw new PHPExcel_Writer_Exception("Could not close zip file {$pFilename}."); } // If a temporary file was used, copy it to the correct file stream if ($originalFilename != $pFilename) { if (copy($pFilename, $originalFilename) === false) { throw new PHPExcel_Writer_Exception("Could not copy temporary zip file {$pFilename} to {$originalFilename}."); } @unlink($pFilename); } } else { throw new PHPExcel_Writer_Exception("PHPExcel object unassigned."); } }
/** * Save PHPExcel to file * * @param string $pFileName * @throws Exception */ public function save($pFilename = null) { if (!is_null($this->_spreadSheet)) { // garbage collect $this->_spreadSheet->garbageCollect(); // If $pFilename is php://output or php://stdout, make it a temporary file... $originalFilename = $pFilename; if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') { $pFilename = @tempnam('./', 'phpxltmp'); if ($pFilename == '') { $pFilename = $originalFilename; } } $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType(); PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL); // Create string lookup table $this->_stringTable = array(); for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) { $this->_stringTable = $this->getWriterPart('StringTable')->createStringTable($this->_spreadSheet->getSheet($i), $this->_stringTable); } // Create styles dictionaries $this->_stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->_spreadSheet)); $this->_fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->_spreadSheet)); $this->_fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->_spreadSheet)); $this->_bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->_spreadSheet)); $this->_numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->_spreadSheet)); // Create drawing dictionary $this->_drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->_spreadSheet)); // Create new ZIP file and open it for writing $objZip = new ZipArchive(); // Try opening the ZIP file if ($objZip->open($pFilename, ZIPARCHIVE::OVERWRITE) !== true) { if ($objZip->open($pFilename, ZIPARCHIVE::CREATE) !== true) { throw new Exception("Could not open " . $pFilename . " for writing."); } } // Add [Content_Types].xml to ZIP file $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->_spreadSheet)); // Add relationships to ZIP file $objZip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->_spreadSheet)); $objZip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->_spreadSheet)); // Add document properties to ZIP file $objZip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->_spreadSheet)); $objZip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->_spreadSheet)); // Add theme to ZIP file $objZip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->_spreadSheet)); // Add string table to ZIP file $objZip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->_stringTable)); // Add styles to ZIP file $objZip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->_spreadSheet)); // Add workbook to ZIP file $objZip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->_spreadSheet)); // Add worksheets for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) { $objZip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->_spreadSheet->getSheet($i), $this->_stringTable)); } // Add worksheet relationships (drawings, ...) for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) { // Add relationships $objZip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->_spreadSheet->getSheet($i), $i + 1)); // Add drawing relationship parts if ($this->_spreadSheet->getSheet($i)->getDrawingCollection()->count() > 0) { // Drawing relationships $objZip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->_spreadSheet->getSheet($i))); // Drawings $objZip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->_spreadSheet->getSheet($i))); } // Add comment relationship parts if (count($this->_spreadSheet->getSheet($i)->getComments()) > 0) { // VML Comments $objZip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->_spreadSheet->getSheet($i))); // Comments $objZip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->_spreadSheet->getSheet($i))); } // Add header/footer relationship parts if (count($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { // VML Drawings $objZip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->_spreadSheet->getSheet($i))); // VML Drawing relationships $objZip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->_spreadSheet->getSheet($i))); // Media foreach ($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { $objZip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath())); } } } // Add media for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) { if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) { $imageContents = null; $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath(); if (strpos($imagePath, 'zip://') !== false) { $imagePath = substr($imagePath, 6); $imagePathSplitted = explode('#', $imagePath); $imageZip = new ZipArchive(); $imageZip->open($imagePathSplitted[0]); $imageContents = $imageZip->getFromName($imagePathSplitted[1]); $imageZip->close(); unset($imageZip); } else { $imageContents = file_get_contents($imagePath); } $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); } else { if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) { ob_start(); call_user_func($this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(), $this->getDrawingHashTable()->getByIndex($i)->getImageResource()); $imageContents = ob_get_contents(); ob_end_clean(); $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); } } } PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType); // Close file if ($objZip->close() === false) { throw new Exception("Could not close zip file {$pFilename}."); } // If a temporary file was used, copy it to the correct file stream if ($originalFilename != $pFilename) { if (copy($pFilename, $originalFilename) === false) { throw new Exception("Could not copy temporary zip file {$pFilename} to {$originalFilename}."); } @unlink($pFilename); } } else { throw new Exception("PHPExcel object unassigned."); } }
/** * 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; } // Construct CSS $css = array(); // Start styles if ($generateSurroundingHTML) { // html { } $css['html'] = 'font-family: Calibri, Arial, Helvetica, sans-serif; '; $css['html'] .= 'font-size: 10pt; '; $css['html'] .= 'background-color: white; '; } // 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 $hashCode = $sheet->getHashCode(); // Build styles // table.sheetXXXXXX { } $css['table.sheet' . $hashCode] = ''; if ($sheet->getShowGridlines()) { $css['table.sheet' . $hashCode] .= 'border: 1px dotted black; '; } $css['table.sheet' . $hashCode] .= 'page-break-after: always; '; // table.sheetXXXXXX td { } $css['table.sheet' . $hashCode . ' td'] = $css['table.sheet' . $hashCode]; // Default column width $columnDimension = $sheet->getDefaultColumnDimension(); $css['table.sheet' . $hashCode . ' td'] .= 'width: ' . PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth()) . 'px; '; if ($columnDimension->getVisible() === false) { $css['table.sheet' . $hashCode . ' td'] .= 'display: none; '; $css['table.sheet' . $hashCode . ' td'] .= 'visibility: hidden; '; } // Calculate column widths $sheet->calculateColumnWidths(); foreach ($sheet->getColumnDimensions() as $columnDimension) { $column = PHPExcel_Cell::columnIndexFromString($columnDimension->getColumnIndex()) - 1; // table.sheetXXXXXX td.columnYYYYYY { } $css['table.sheet' . $hashCode . ' td.column' . $column] = 'width: ' . PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth()) . 'px; '; if ($columnDimension->getVisible() === false) { $css['table.sheet' . $hashCode . ' td.column' . $column] .= 'display: none; '; $css['table.sheet' . $hashCode . ' td.column' . $column] .= 'visibility: hidden; '; } } // Default row height $rowDimension = $sheet->getDefaultRowDimension(); // table.sheetXXXXXX tr { } $css['table.sheet' . $hashCode . ' tr'] = ''; // height is disproportionately large $px_height = round(PHPExcel_Shared_Drawing::cellDimensionToPixels($rowDimension->getRowHeight()) / 12); $css['table.sheet' . $hashCode . ' tr'] .= 'height: ' . $px_height . 'px; '; if ($rowDimension->getVisible() === false) { $css['table.sheet' . $hashCode . ' tr'] .= 'display: none; '; $css['table.sheet' . $hashCode . ' tr'] .= 'visibility: hidden; '; } // Calculate row heights foreach ($sheet->getRowDimensions() as $rowDimension) { // table.sheetXXXXXX tr.rowYYYYYY { } $css['table.sheet' . $hashCode . ' tr.row' . ($rowDimension->getRowIndex() - 1)] = ''; // height is disproportionately large $px_height = round(PHPExcel_Shared_Drawing::cellDimensionToPixels($rowDimension->getRowHeight()) / 12); $css['table.sheet' . $hashCode . ' tr.row' . ($rowDimension->getRowIndex() - 1)] .= 'height: ' . $px_height . 'px; '; if ($rowDimension->getVisible() === false) { $css['table.sheet' . $hashCode . ' tr.row' . ($rowDimension->getRowIndex() - 1)] .= 'display: none; '; $css['table.sheet' . $hashCode . ' tr.row' . ($rowDimension->getRowIndex() - 1)] .= 'visibility: hidden; '; } } // Calculate cell style hashes $cellStyleHashes = new PHPExcel_HashTable(); $aStyles = $sheet->getStyles(); $cellStyleHashes->addFromSource($aStyles); $addedStyles = array(); foreach ($aStyles as $style) { if (isset($addedStyles[$style->getHashIndex()])) { continue; } $css['style' . $style->getHashIndex()] = $this->_createCSSStyle($style); $addedStyles[$style->getHashIndex()] = true; } } // Cache if (is_null($this->_cssStyles)) { $this->_cssStyles = $css; } // Return return $css; }
/** * Write styles to file * * @param mixed $pFileHandle PHP filehandle * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet * @throws Exception */ private function _writeStyles($pFileHandle = null, PHPExcel_Worksheet $pSheet) { if (!is_null($pFileHandle)) { // Construct HTML $html = ''; // Start styles $html .= ' <style>' . "\r\n"; $html .= ' <!--' . "\r\n"; $html .= ' html {' . "\r\n"; $html .= ' font-family: Calibri, Arial, Helvetica, Sans Serif;' . "\r\n"; $html .= ' font-size: 10pt;' . "\r\n"; $html .= ' background-color: white;' . "\r\n"; $html .= ' }' . "\r\n"; $html .= ' table.sheet, table.sheet td {' . "\r\n"; if ($pSheet->getShowGridlines()) { $html .= ' border: 1px dotted black;' . "\r\n"; } $html .= ' }' . "\r\n"; // Calculate column widths $pSheet->calculateColumnWidths(); foreach ($pSheet->getColumnDimensions() as $columnDimension) { $column = PHPExcel_Cell::columnIndexFromString($columnDimension->getColumnIndex()) - 1; $html .= ' td.column' . $column . ' {' . "\r\n"; $html .= ' width: ' . PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth()) . 'px;' . "\r\n"; if ($columnDimension->getVisible() === false) { $html .= ' display: none;' . "\r\n"; $html .= ' visibility: hidden;' . "\r\n"; } $html .= ' }' . "\r\n"; } // Calculate row heights foreach ($pSheet->getRowDimensions() as $rowDimension) { $html .= ' tr.row' . ($rowDimension->getRowIndex() - 1) . ' {' . "\r\n"; // height is disproportionately large $px_height = round(PHPExcel_Shared_Drawing::cellDimensionToPixels($rowDimension->getRowHeight()) / 12); $html .= ' height: ' . $px_height . 'px;' . "\r\n"; if ($rowDimension->getVisible() === false) { $html .= ' display: none;' . "\r\n"; $html .= ' visibility: hidden;' . "\r\n"; } $html .= ' }' . "\r\n"; } // Calculate cell style hashes $cellStyleHashes = new PHPExcel_HashTable(); $cellStyleHashes->addFromSource($pSheet->getStyles()); for ($i = 0; $i < $cellStyleHashes->count(); $i++) { $html .= $this->_createCSSStyle($cellStyleHashes->getByIndex($i)); } // End styles $html .= ' -->' . "\r\n"; $html .= ' </style>' . "\r\n"; // Write to file fwrite($pFileHandle, $html); } else { throw new Exception("Invalid parameters passed."); } }
/** * Generate CSS styles * * @param boolean $generateSurroundingHTML Generate surrounding HTML tags? (<style> and </style>) * @return string * @throws Exception */ public function generateStyles($generateSurroundingHTML = true) { // PHPExcel object known? if (is_null($this->_phpExcel)) { throw new Exception('Internal PHPExcel object not set to an instance of an object.'); } // Construct HTML $html = ''; // Start styles if ($generateSurroundingHTML) { $html .= ' <style>' . "\r\n"; $html .= ' <!--' . "\r\n"; $html .= ' html {' . "\r\n"; $html .= ' font-family: Calibri, Arial, Helvetica, Sans Serif;' . "\r\n"; $html .= ' font-size: 10pt;' . "\r\n"; $html .= ' background-color: white;' . "\r\n"; $html .= ' }' . "\r\n"; } // Write styles per sheet foreach ($this->_phpExcel->getAllSheets() as $sheet) { // Calculate hash code $hashCode = $sheet->getHashCode(); // Write styles $html .= ' table.sheet' . $hashCode . ', table.sheet' . $hashCode . ' td {' . "\r\n"; if ($sheet->getShowGridlines()) { $html .= ' border: 1px dotted black;' . "\r\n"; } $html .= ' page-break-after: always;' . "\r\n"; $html .= ' }' . "\r\n"; // Default column width $columnDimension = $sheet->getDefaultColumnDimension(); $html .= ' table.sheet' . $hashCode . ' td {' . "\r\n"; $html .= ' width: ' . PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth()) . 'px;' . "\r\n"; if ($columnDimension->getVisible() === false) { $html .= ' display: none;' . "\r\n"; $html .= ' visibility: hidden;' . "\r\n"; } $html .= ' }' . "\r\n"; // Calculate column widths $sheet->calculateColumnWidths(); foreach ($sheet->getColumnDimensions() as $columnDimension) { $column = PHPExcel_Cell::columnIndexFromString($columnDimension->getColumnIndex()) - 1; $html .= ' table.sheet' . $hashCode . ' td.column' . $column . ' {' . "\r\n"; $html .= ' width: ' . PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth()) . 'px;' . "\r\n"; if ($columnDimension->getVisible() === false) { $html .= ' display: none;' . "\r\n"; $html .= ' visibility: hidden;' . "\r\n"; } $html .= ' }' . "\r\n"; } // Default row height $rowDimension = $sheet->getDefaultRowDimension(); $html .= ' table.sheet' . $hashCode . ' tr {' . "\r\n"; // height is disproportionately large $px_height = round( PHPExcel_Shared_Drawing::cellDimensionToPixels($rowDimension->getRowHeight()) / 12 ); $html .= ' height: ' . $px_height . 'px;' . "\r\n"; if ($rowDimension->getVisible() === false) { $html .= ' display: none;' . "\r\n"; $html .= ' visibility: hidden;' . "\r\n"; } $html .= ' }' . "\r\n"; // Calculate row heights foreach ($sheet->getRowDimensions() as $rowDimension) { $html .= ' table.sheet' . $hashCode . ' tr.row' . ($rowDimension->getRowIndex() - 1) . ' {' . "\r\n"; // height is disproportionately large $px_height = round( PHPExcel_Shared_Drawing::cellDimensionToPixels($rowDimension->getRowHeight()) / 12 ); $html .= ' height: ' . $px_height . 'px;' . "\r\n"; if ($rowDimension->getVisible() === false) { $html .= ' display: none;' . "\r\n"; $html .= ' visibility: hidden;' . "\r\n"; } $html .= ' }' . "\r\n"; } // Calculate cell style hashes $cellStyleHashes = new PHPExcel_HashTable(); $cellStyleHashes->addFromSource( $sheet->getStyles() ); for ($i = 0; $i < $cellStyleHashes->count(); $i++) { $html .= $this->_createCSSStyle( $cellStyleHashes->getByIndex($i) ); } } // End styles if ($generateSurroundingHTML) { $html .= ' -->' . "\r\n"; $html .= ' </style>' . "\r\n"; } // Return return $html; }
/** * Save PHPExcel to file * * @param string $pFileName * @throws Exception */ public function save($pFilename = null) { $phpExcel = $this->_phpExcel; $workbook = new PHPExcel_Writer_Excel5_Workbook($pFilename, $phpExcel); $workbook->setVersion(8); // Set temp dir if ($this->_tempDir != '') { $workbook->setTempDir($this->_tempDir); } $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType(); PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL); // Add 15 style Xf's plus 1 cell Xf. Why? for ($i = 0; $i < 15; ++$i) { $workbook->addXfWriter($phpExcel->getSheet(0)->getDefaultStyle(), true); } $workbook->addXfWriter($phpExcel->getSheet(0)->getDefaultStyle()); // Style dictionary $xfIndexes = array(); $allStyles = $this->_allStyles($this->_phpExcel); $cellStyleHashes = new PHPExcel_HashTable(); $cellStyleHashes->addFromSource($allStyles); $addedStyles = array(); foreach ($allStyles as $style) { $styleHashIndex = $style->getHashIndex(); if (isset($addedStyles[$styleHashIndex])) { continue; } // mapping between PHPExcel style hash index and BIFF XF index $xfIndexes[$styleHashIndex] = $workbook->addXfWriter($style); $addedStyles[$style->getHashIndex()] = true; } // Add empty sheets foreach ($phpExcel->getSheetNames() as $sheetIndex => $sheetName) { $phpSheet = $phpExcel->getSheet($sheetIndex); $worksheet = $workbook->addWorksheet($phpSheet, $xfIndexes); } PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType); $workbook->close(); }
/** * 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; } // Construct CSS $css = array(); // Start styles if ($generateSurroundingHTML) { // html { } $css['html'] = 'font-family: Calibri, Arial, Helvetica, sans-serif; '; $css['html'] .= 'font-size: 10pt; '; $css['html'] .= 'background-color: white; '; } // 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 $hashCode = $sheet->getHashCode(); // Build styles // table.sheetXXXXXX { } $css['table.sheet' . $hashCode] = ''; if ($sheet->getShowGridlines()) { $css['table.sheet' . $hashCode] .= 'border: 1px dotted black; '; } $css['table.sheet' . $hashCode] .= 'page-break-after: always; '; // table.sheetXXXXXX td { } $css['table.sheet' . $hashCode . ' td'] = $css['table.sheet' . $hashCode]; // Calculate column widths $sheet->calculateColumnWidths(); // col elements, initialize $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn()) - 1; for ($column = 0; $column <= $highestColumnIndex; ++$column) { $this->_columnWidths[$hashCode][$column] = 42; // approximation $css['table.sheet' . $hashCode . ' col.col' . $column] = 'width: 42pt'; } // col elements, loop through columnDimensions and set width foreach ($sheet->getColumnDimensions() as $columnDimension) { if (($width = PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth())) >= 0) { $width = PHPExcel_Shared_Drawing::pixelsToPoints($width); $column = PHPExcel_Cell::columnIndexFromString($columnDimension->getColumnIndex()) - 1; $this->_columnWidths[$hashCode][$column] = $width; $css['table.sheet' . $hashCode . ' col.col' . $column] = 'width: ' . $width . 'pt; '; if ($columnDimension->getVisible() === false) { $css['table.sheet' . $hashCode . ' col.col' . $column] .= 'visibility: collapse; '; $css['table.sheet' . $hashCode . ' col.col' . $column] .= '*display: none; '; // target IE6+7 } } } // Default row height $rowDimension = $sheet->getDefaultRowDimension(); // table.sheetXXXXXX tr { } $css['table.sheet' . $hashCode . ' tr'] = ''; // height is disproportionately large $px_height = round(PHPExcel_Shared_Drawing::cellDimensionToPixels($rowDimension->getRowHeight()) / 12); $css['table.sheet' . $hashCode . ' tr'] .= 'height: ' . $px_height . 'px; '; if ($rowDimension->getVisible() === false) { $css['table.sheet' . $hashCode . ' tr'] .= 'display: none; '; $css['table.sheet' . $hashCode . ' tr'] .= 'visibility: hidden; '; } // Calculate row heights foreach ($sheet->getRowDimensions() as $rowDimension) { // table.sheetXXXXXX tr.rowYYYYYY { } $css['table.sheet' . $hashCode . ' tr.row' . ($rowDimension->getRowIndex() - 1)] = ''; // height is disproportionately large $px_height = round(PHPExcel_Shared_Drawing::cellDimensionToPixels($rowDimension->getRowHeight()) / 12); $css['table.sheet' . $hashCode . ' tr.row' . ($rowDimension->getRowIndex() - 1)] .= 'height: ' . $px_height . 'px; '; if ($rowDimension->getVisible() === false) { $css['table.sheet' . $hashCode . ' tr.row' . ($rowDimension->getRowIndex() - 1)] .= 'display: none; '; $css['table.sheet' . $hashCode . ' tr.row' . ($rowDimension->getRowIndex() - 1)] .= 'visibility: hidden; '; } } // .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 $cellStyleHashes = new PHPExcel_HashTable(); $aStyles = $sheet->getStyles(); $cellStyleHashes->addFromSource($aStyles); $addedStyles = array(); foreach ($aStyles as $style) { if (isset($addedStyles[$style->getHashIndex()])) { continue; } $css['style' . $style->getHashIndex()] = $this->_createCSSStyle($style); $addedStyles[$style->getHashIndex()] = true; } } // Cache if (is_null($this->_cssStyles)) { $this->_cssStyles = $css; } // Return return $css; }
/** * Save PHPExcel to file * * @param string $pFileName * @throws Exception */ public function save($pFilename = null) { // check for iconv support if (!function_exists('iconv')) { throw new Exception("Cannot write .xls file without PHP support for iconv"); } $this->_colors = array(); $phpExcel = $this->_phpExcel; $workbook = new PHPExcel_Writer_Excel5_Workbook($pFilename, $phpExcel); $workbook->setVersion(8); // Set temp dir if ($this->_tempDir != '') { $workbook->setTempDir($this->_tempDir); } $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType(); PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL); // Add empty sheets foreach ($phpExcel->getSheetNames() as $sheetIndex => $sheetName) { $phpSheet = $phpExcel->getSheet($sheetIndex); $worksheet = $workbook->addWorksheet($sheetName, $phpSheet); } $allWorksheets = $workbook->worksheets(); $formats = array(); // Add full sheet data foreach ($phpExcel->getSheetNames() as $sheetIndex => $sheetName) { $phpSheet = $phpExcel->getSheet($sheetIndex); $worksheet = $allWorksheets[$sheetIndex]; // Default style $emptyStyle = $phpSheet->getDefaultStyle(); $aStyles = $phpSheet->getStyles(); // Calculate cell style hashes $cellStyleHashes = new PHPExcel_HashTable(); $aStyles = $phpSheet->getStyles(); $cellStyleHashes->addFromSource($aStyles); $addedStyles = array(); foreach ($aStyles as $style) { $styleHashIndex = $style->getHashIndex(); if (isset($addedStyles[$styleHashIndex])) { continue; } $formats[$styleHashIndex] = $workbook->addFormat(array('HAlign' => $style->getAlignment()->getHorizontal(), 'VAlign' => $this->_mapVAlign($style->getAlignment()->getVertical()), 'TextRotation' => $style->getAlignment()->getTextRotation(), 'Bold' => $style->getFont()->getBold(), 'FontFamily' => $style->getFont()->getName(), 'Color' => $this->_addColor($workbook, $style->getFont()->getColor()->getRGB()), 'Underline' => $this->_mapUnderline($style->getFont()->getUnderline()), 'Size' => $style->getFont()->getSize(), 'NumFormat' => $style->getNumberFormat()->getFormatCode(), 'Bottom' => $this->_mapBorderStyle($style->getBorders()->getBottom()->getBorderStyle()), 'Top' => $this->_mapBorderStyle($style->getBorders()->getTop()->getBorderStyle()), 'Left' => $this->_mapBorderStyle($style->getBorders()->getLeft()->getBorderStyle()), 'Right' => $this->_mapBorderStyle($style->getBorders()->getRight()->getBorderStyle()), 'BottomColor' => $this->_addColor($workbook, $style->getBorders()->getBottom()->getColor()->getRGB()), 'TopColor' => $this->_addColor($workbook, $style->getBorders()->getTop()->getColor()->getRGB()), 'RightColor' => $this->_addColor($workbook, $style->getBorders()->getRight()->getColor()->getRGB()), 'LeftColor' => $this->_addColor($workbook, $style->getBorders()->getLeft()->getColor()->getRGB()), 'FgColor' => $this->_addColor($workbook, $style->getFill()->getStartColor()->getRGB()), 'BgColor' => $this->_addColor($workbook, $style->getFill()->getEndColor()->getRGB()), 'Pattern' => $this->_mapFillType($style->getFill()->getFillType()))); if ($style->getAlignment()->getWrapText()) { $formats[$styleHashIndex]->setTextWrap(); } $formats[$styleHashIndex]->setIndent($style->getAlignment()->getIndent()); if ($style->getAlignment()->getShrinkToFit()) { $formats[$styleHashIndex]->setShrinkToFit(); } if ($style->getFont()->getItalic()) { $formats[$styleHashIndex]->setItalic(); } if ($style->getFont()->getStriketrough()) { $formats[$styleHashIndex]->setStrikeOut(); } if ($style->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_UNPROTECTED) { $formats[$styleHashIndex]->setUnlocked(); } if ($style->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED) { $formats[$styleHashIndex]->setHidden(); } $addedStyles[$style->getHashIndex()] = true; } // Active sheet if ($sheetIndex == $phpExcel->getActiveSheetIndex()) { $worksheet->activate(); } // initialize first, last, row and column index, needed for DIMENSION record $firstRowIndex = 0; $lastRowIndex = -1; $firstColumnIndex = 0; $lastColumnIndex = -1; foreach ($phpSheet->getCellCollection() as $cell) { $row = $cell->getRow() - 1; $column = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1; // Don't break Excel! if ($row + 1 >= 65569) { break; } $firstRowIndex = min($firstRowIndex, $row); $lastRowIndex = max($lastRowIndex, $row); $firstColumnIndex = min($firstColumnIndex, $column); $lastColumnIndex = max($lastColumnIndex, $column); $style = $emptyStyle; if (isset($aStyles[$cell->getCoordinate()])) { $style = $aStyles[$cell->getCoordinate()]; } $styleHashIndex = $style->getHashIndex(); // Write cell value if ($cell->getValue() instanceof PHPExcel_RichText) { $worksheet->write($row, $column, $cell->getValue()->getPlainText(), $formats[$styleHashIndex]); } else { switch ($cell->getDatatype()) { case PHPExcel_Cell_DataType::TYPE_STRING: if ($cell->getValue() === '' or $cell->getValue() === null) { $worksheet->writeBlank($row, $column, $formats[$styleHashIndex]); } else { $worksheet->writeString($row, $column, $cell->getValue(), $formats[$styleHashIndex]); } break; case PHPExcel_Cell_DataType::TYPE_FORMULA: $worksheet->writeFormula($row, $column, $cell->getValue(), $formats[$styleHashIndex]); break; case PHPExcel_Cell_DataType::TYPE_BOOL: $worksheet->writeBoolErr($row, $column, $cell->getValue(), 0, $formats[$styleHashIndex]); break; case PHPExcel_Cell_DataType::TYPE_ERROR: $worksheet->writeBoolErr($row, $column, $this->_mapErrorCode($cell->getValue()), 1, $formats[$styleHashIndex]); break; default: $worksheet->write($row, $column, $cell->getValue(), $formats[$styleHashIndex], $style->getNumberFormat()->getFormatCode()); break; } // Hyperlink? if ($cell->hasHyperlink()) { $worksheet->writeUrl($row, $column, str_replace('sheet://', 'internal:', $cell->getHyperlink()->getUrl())); } } } // set the worksheet dimension for the DIMENSION record $worksheet->setDimensions($firstRowIndex, $lastRowIndex, $firstColumnIndex, $lastColumnIndex); $phpSheet->calculateColumnWidths(); // Column dimensions foreach ($phpSheet->getColumnDimensions() as $columnDimension) { $column = PHPExcel_Cell::columnIndexFromString($columnDimension->getColumnIndex()) - 1; if ($column < 256) { if ($columnDimension->getWidth() >= 0) { $width = $columnDimension->getWidth(); } else { if ($phpSheet->getDefaultColumnDimension()->getWidth() >= 0) { $width = $phpSheet->getDefaultColumnDimension()->getWidth(); } else { $width = 8; } } $worksheet->setColumn($column, $column, $width, null, $columnDimension->getVisible() ? '0' : '1', $columnDimension->getOutlineLevel()); } } // Row dimensions foreach ($phpSheet->getRowDimensions() as $rowDimension) { $worksheet->setRow($rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), null, $rowDimension->getVisible() ? '0' : '1', $rowDimension->getOutlineLevel()); } foreach ($phpSheet->getDrawingCollection() as $drawing) { list($column, $row) = PHPExcel_Cell::coordinateFromString($drawing->getCoordinates()); if ($drawing instanceof PHPExcel_Worksheet_Drawing) { $filename = $drawing->getPath(); list($imagesx, $imagesy, $imageFormat) = getimagesize($filename); switch ($imageFormat) { case 1: $image = imagecreatefromgif($filename); break; case 2: $image = imagecreatefromjpeg($filename); break; case 3: $image = imagecreatefrompng($filename); break; default: continue 2; } } else { if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) { $image = $drawing->getImageResource(); $imagesx = imagesx($image); $imagesy = imagesy($image); } } $worksheet->insertBitmap($row - 1, PHPExcel_Cell::columnIndexFromString($column) - 1, $image, $drawing->getOffsetX(), $drawing->getOffsetY(), $drawing->getWidth() / $imagesx, $drawing->getHeight() / $imagesy); } } PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType); $workbook->close(); }
/** * Save PHPExcel to file * * @param string $pFileName * @throws Exception */ public function save($pFilename = null) { if (!is_null($this->_spreadSheet)) { // Create string lookup table $this->_stringTable = array(); for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); $i++) { $this->_stringTable = $this->getWriterPart('StringTable')->createStringTable($this->_spreadSheet->getSheet($i), $this->_stringTable); } // Create styles dictionaries $this->_stylesHashTable->addFromSource($this->getWriterPart('Style')->allStyles($this->_spreadSheet)); $this->_stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->_spreadSheet)); $this->_fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->_spreadSheet)); $this->_fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->_spreadSheet)); $this->_bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->_spreadSheet)); $this->_numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->_spreadSheet)); // Create drawing dictionary $this->_drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->_spreadSheet)); // Create new ZIP file and open it for writing $objZip = new ZipArchive(); // Try opening the ZIP file if ($objZip->open($pFilename, ZIPARCHIVE::OVERWRITE) !== true) { throw new Exception("Could not open " . $pFilename . " for writing."); } // Add [Content_Types].xml to ZIP file $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->_spreadSheet)); // Add relationships to ZIP file $objZip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->_spreadSheet)); $objZip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->_spreadSheet)); // Add document properties to ZIP file $objZip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->_spreadSheet)); $objZip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->_spreadSheet)); // Add theme to ZIP file $objZip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->_spreadSheet)); // Add string table to ZIP file $objZip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->_stringTable)); // Add styles to ZIP file $objZip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->_spreadSheet)); // Add workbook to ZIP file $objZip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->_spreadSheet)); // Add worksheets for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); $i++) { $objZip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->_spreadSheet->getSheet($i), $this->_stringTable)); } // Add worksheet relationships (drawings, ...) for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); $i++) { // Add relationships if ($this->_spreadSheet->getSheet($i)->getDrawingCollection()->count() > 0) { // Worksheet relationships $objZip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->_spreadSheet->getSheet($i), $i + 1)); } // Add drawing relationship parts if ($this->_spreadSheet->getSheet($i)->getDrawingCollection()->count() > 0) { // Drawing relationships $objZip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->_spreadSheet->getSheet($i))); // Drawings $objZip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->_spreadSheet->getSheet($i))); } // Add comment relationship parts if (count($this->_spreadSheet->getSheet($i)->getComments()) > 0) { // VML Comments $objZip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->_spreadSheet->getSheet($i))); // Comments $objZip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->_spreadSheet->getSheet($i))); } } // Add media for ($i = 0; $i < $this->getDrawingHashTable()->count(); $i++) { if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) { $objZip->addFromString('xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getFilename(), file_get_contents($this->getDrawingHashTable()->getByIndex($i)->getPath())); } //The line underneath does not support adding a file from a ZIP archive, the line above does! //$objZip->addFile($this->getDrawingHashTable()->getByIndex($i)->getPath(), 'xl/media/' . $this->getDrawingHashTable()->getByIndex($i)->getFilename()); } // Close file if ($objZip->close() === false) { throw new Exception("Could not close zip file {$pFilename}."); } } else { throw new Exception("PHPExcel object unassigned."); } }