Excel2007.php 18 KB

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