Xlsx.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. <?php
  2. namespace PhpOffice\PhpSpreadsheet\Writer;
  3. use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
  4. use PhpOffice\PhpSpreadsheet\Calculation\Functions;
  5. use PhpOffice\PhpSpreadsheet\HashTable;
  6. use PhpOffice\PhpSpreadsheet\Shared\File;
  7. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  8. use PhpOffice\PhpSpreadsheet\Worksheet\Drawing as WorksheetDrawing;
  9. use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
  10. use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
  11. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Chart;
  12. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Comments;
  13. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\ContentTypes;
  14. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\DocProps;
  15. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Drawing;
  16. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Rels;
  17. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsRibbon;
  18. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\RelsVBA;
  19. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\StringTable;
  20. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Style;
  21. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Theme;
  22. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Workbook;
  23. use PhpOffice\PhpSpreadsheet\Writer\Xlsx\Worksheet;
  24. use ZipArchive;
  25. class Xlsx extends BaseWriter
  26. {
  27. /**
  28. * Office2003 compatibility.
  29. *
  30. * @var bool
  31. */
  32. private $office2003compatibility = false;
  33. /**
  34. * Private writer parts.
  35. *
  36. * @var Xlsx\WriterPart[]
  37. */
  38. private $writerParts = [];
  39. /**
  40. * Private Spreadsheet.
  41. *
  42. * @var Spreadsheet
  43. */
  44. private $spreadSheet;
  45. /**
  46. * Private string table.
  47. *
  48. * @var string[]
  49. */
  50. private $stringTable = [];
  51. /**
  52. * Private unique Conditional HashTable.
  53. *
  54. * @var HashTable
  55. */
  56. private $stylesConditionalHashTable;
  57. /**
  58. * Private unique Style HashTable.
  59. *
  60. * @var HashTable
  61. */
  62. private $styleHashTable;
  63. /**
  64. * Private unique Fill HashTable.
  65. *
  66. * @var HashTable
  67. */
  68. private $fillHashTable;
  69. /**
  70. * Private unique \PhpOffice\PhpSpreadsheet\Style\Font HashTable.
  71. *
  72. * @var HashTable
  73. */
  74. private $fontHashTable;
  75. /**
  76. * Private unique Borders HashTable.
  77. *
  78. * @var HashTable
  79. */
  80. private $bordersHashTable;
  81. /**
  82. * Private unique NumberFormat HashTable.
  83. *
  84. * @var HashTable
  85. */
  86. private $numFmtHashTable;
  87. /**
  88. * Private unique \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable.
  89. *
  90. * @var HashTable
  91. */
  92. private $drawingHashTable;
  93. /**
  94. * Create a new Xlsx Writer.
  95. *
  96. * @param Spreadsheet $spreadsheet
  97. */
  98. public function __construct(Spreadsheet $spreadsheet)
  99. {
  100. // Assign PhpSpreadsheet
  101. $this->setSpreadsheet($spreadsheet);
  102. $writerPartsArray = [
  103. 'stringtable' => StringTable::class,
  104. 'contenttypes' => ContentTypes::class,
  105. 'docprops' => DocProps::class,
  106. 'rels' => Rels::class,
  107. 'theme' => Theme::class,
  108. 'style' => Style::class,
  109. 'workbook' => Workbook::class,
  110. 'worksheet' => Worksheet::class,
  111. 'drawing' => Drawing::class,
  112. 'comments' => Comments::class,
  113. 'chart' => Chart::class,
  114. 'relsvba' => RelsVBA::class,
  115. 'relsribbonobjects' => RelsRibbon::class,
  116. ];
  117. // Initialise writer parts
  118. // and Assign their parent IWriters
  119. foreach ($writerPartsArray as $writer => $class) {
  120. $this->writerParts[$writer] = new $class($this);
  121. }
  122. $hashTablesArray = ['stylesConditionalHashTable', 'fillHashTable', 'fontHashTable',
  123. 'bordersHashTable', 'numFmtHashTable', 'drawingHashTable',
  124. 'styleHashTable',
  125. ];
  126. // Set HashTable variables
  127. foreach ($hashTablesArray as $tableName) {
  128. $this->$tableName = new HashTable();
  129. }
  130. }
  131. /**
  132. * Get writer part.
  133. *
  134. * @param string $pPartName Writer part name
  135. *
  136. * @return \PhpOffice\PhpSpreadsheet\Writer\Xlsx\WriterPart
  137. */
  138. public function getWriterPart($pPartName)
  139. {
  140. if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) {
  141. return $this->writerParts[strtolower($pPartName)];
  142. }
  143. return null;
  144. }
  145. /**
  146. * Save PhpSpreadsheet to file.
  147. *
  148. * @param string $pFilename
  149. *
  150. * @throws WriterException
  151. */
  152. public function save($pFilename)
  153. {
  154. if ($this->spreadSheet !== null) {
  155. // garbage collect
  156. $this->spreadSheet->garbageCollect();
  157. // If $pFilename is php://output or php://stdout, make it a temporary file...
  158. $originalFilename = $pFilename;
  159. if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') {
  160. $pFilename = @tempnam(File::sysGetTempDir(), 'phpxltmp');
  161. if ($pFilename == '') {
  162. $pFilename = $originalFilename;
  163. }
  164. }
  165. $saveDebugLog = Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog();
  166. Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false);
  167. $saveDateReturnType = Functions::getReturnDateType();
  168. Functions::setReturnDateType(Functions::RETURNDATE_EXCEL);
  169. // Create string lookup table
  170. $this->stringTable = [];
  171. for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
  172. $this->stringTable = $this->getWriterPart('StringTable')->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable);
  173. }
  174. // Create styles dictionaries
  175. $this->styleHashTable->addFromSource($this->getWriterPart('Style')->allStyles($this->spreadSheet));
  176. $this->stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->spreadSheet));
  177. $this->fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->spreadSheet));
  178. $this->fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->spreadSheet));
  179. $this->bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->spreadSheet));
  180. $this->numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->spreadSheet));
  181. // Create drawing dictionary
  182. $this->drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->spreadSheet));
  183. $zip = new ZipArchive();
  184. if (file_exists($pFilename)) {
  185. unlink($pFilename);
  186. }
  187. // Try opening the ZIP file
  188. if ($zip->open($pFilename, ZipArchive::OVERWRITE) !== true) {
  189. if ($zip->open($pFilename, ZipArchive::CREATE) !== true) {
  190. throw new WriterException('Could not open ' . $pFilename . ' for writing.');
  191. }
  192. }
  193. // Add [Content_Types].xml to ZIP file
  194. $zip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->spreadSheet, $this->includeCharts));
  195. //if hasMacros, add the vbaProject.bin file, Certificate file(if exists)
  196. if ($this->spreadSheet->hasMacros()) {
  197. $macrosCode = $this->spreadSheet->getMacrosCode();
  198. if ($macrosCode !== null) {
  199. // we have the code ?
  200. $zip->addFromString('xl/vbaProject.bin', $macrosCode); //allways in 'xl', allways named vbaProject.bin
  201. if ($this->spreadSheet->hasMacrosCertificate()) {
  202. //signed macros ?
  203. // Yes : add the certificate file and the related rels file
  204. $zip->addFromString('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate());
  205. $zip->addFromString('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet));
  206. }
  207. }
  208. }
  209. //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels)
  210. if ($this->spreadSheet->hasRibbon()) {
  211. $tmpRibbonTarget = $this->spreadSheet->getRibbonXMLData('target');
  212. $zip->addFromString($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data'));
  213. if ($this->spreadSheet->hasRibbonBinObjects()) {
  214. $tmpRootPath = dirname($tmpRibbonTarget) . '/';
  215. $ribbonBinObjects = $this->spreadSheet->getRibbonBinObjects('data'); //the files to write
  216. foreach ($ribbonBinObjects as $aPath => $aContent) {
  217. $zip->addFromString($tmpRootPath . $aPath, $aContent);
  218. }
  219. //the rels for files
  220. $zip->addFromString($tmpRootPath . '_rels/' . basename($tmpRibbonTarget) . '.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet));
  221. }
  222. }
  223. // Add relationships to ZIP file
  224. $zip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->spreadSheet));
  225. $zip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->spreadSheet));
  226. // Add document properties to ZIP file
  227. $zip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->spreadSheet));
  228. $zip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->spreadSheet));
  229. $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->spreadSheet);
  230. if ($customPropertiesPart !== null) {
  231. $zip->addFromString('docProps/custom.xml', $customPropertiesPart);
  232. }
  233. // Add theme to ZIP file
  234. $zip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->spreadSheet));
  235. // Add string table to ZIP file
  236. $zip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->stringTable));
  237. // Add styles to ZIP file
  238. $zip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->spreadSheet));
  239. // Add workbook to ZIP file
  240. $zip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas));
  241. $chartCount = 0;
  242. // Add worksheets
  243. for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
  244. $zip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts));
  245. if ($this->includeCharts) {
  246. $charts = $this->spreadSheet->getSheet($i)->getChartCollection();
  247. if (count($charts) > 0) {
  248. foreach ($charts as $chart) {
  249. $zip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas));
  250. ++$chartCount;
  251. }
  252. }
  253. }
  254. }
  255. $chartRef1 = 0;
  256. // Add worksheet relationships (drawings, ...)
  257. for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) {
  258. // Add relationships
  259. $zip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts));
  260. // Add unparsedLoadedData
  261. $sheetCodeName = $this->spreadSheet->getSheet($i)->getCodeName();
  262. $unparsedLoadedData = $this->spreadSheet->getUnparsedLoadedData();
  263. if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'])) {
  264. foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['ctrlProps'] as $ctrlProp) {
  265. $zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']);
  266. }
  267. }
  268. if (isset($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'])) {
  269. foreach ($unparsedLoadedData['sheets'][$sheetCodeName]['printerSettings'] as $ctrlProp) {
  270. $zip->addFromString($ctrlProp['filePath'], $ctrlProp['content']);
  271. }
  272. }
  273. $drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection();
  274. $drawingCount = count($drawings);
  275. if ($this->includeCharts) {
  276. $chartCount = $this->spreadSheet->getSheet($i)->getChartCount();
  277. }
  278. // Add drawing and image relationship parts
  279. if (($drawingCount > 0) || ($chartCount > 0)) {
  280. // Drawing relationships
  281. $zip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts));
  282. // Drawings
  283. $zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
  284. } elseif (isset($unparsedLoadedData['sheets'][$sheetCodeName]['drawingAlternateContents'])) {
  285. // Drawings
  286. $zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
  287. }
  288. // Add comment relationship parts
  289. if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) {
  290. // VML Comments
  291. $zip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i)));
  292. // Comments
  293. $zip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i)));
  294. }
  295. // Add unparsed relationship parts
  296. if (isset($unparsedLoadedData['sheets'][$this->spreadSheet->getSheet($i)->getCodeName()]['vmlDrawings'])) {
  297. foreach ($unparsedLoadedData['sheets'][$this->spreadSheet->getSheet($i)->getCodeName()]['vmlDrawings'] as $vmlDrawing) {
  298. $zip->addFromString($vmlDrawing['filePath'], $vmlDrawing['content']);
  299. }
  300. }
  301. // Add header/footer relationship parts
  302. if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
  303. // VML Drawings
  304. $zip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i)));
  305. // VML Drawing relationships
  306. $zip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i)));
  307. // Media
  308. foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
  309. $zip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
  310. }
  311. }
  312. }
  313. // Add media
  314. for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
  315. if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) {
  316. $imageContents = null;
  317. $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
  318. if (strpos($imagePath, 'zip://') !== false) {
  319. $imagePath = substr($imagePath, 6);
  320. $imagePathSplitted = explode('#', $imagePath);
  321. $imageZip = new ZipArchive();
  322. $imageZip->open($imagePathSplitted[0]);
  323. $imageContents = $imageZip->getFromName($imagePathSplitted[1]);
  324. $imageZip->close();
  325. unset($imageZip);
  326. } else {
  327. $imageContents = file_get_contents($imagePath);
  328. }
  329. $zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
  330. } elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) {
  331. ob_start();
  332. call_user_func(
  333. $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(),
  334. $this->getDrawingHashTable()->getByIndex($i)->getImageResource()
  335. );
  336. $imageContents = ob_get_contents();
  337. ob_end_clean();
  338. $zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
  339. }
  340. }
  341. Functions::setReturnDateType($saveDateReturnType);
  342. Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
  343. // Close file
  344. if ($zip->close() === false) {
  345. throw new WriterException("Could not close zip file $pFilename.");
  346. }
  347. // If a temporary file was used, copy it to the correct file stream
  348. if ($originalFilename != $pFilename) {
  349. if (copy($pFilename, $originalFilename) === false) {
  350. throw new WriterException("Could not copy temporary zip file $pFilename to $originalFilename.");
  351. }
  352. @unlink($pFilename);
  353. }
  354. } else {
  355. throw new WriterException('PhpSpreadsheet object unassigned.');
  356. }
  357. }
  358. /**
  359. * Get Spreadsheet object.
  360. *
  361. * @throws WriterException
  362. *
  363. * @return Spreadsheet
  364. */
  365. public function getSpreadsheet()
  366. {
  367. if ($this->spreadSheet !== null) {
  368. return $this->spreadSheet;
  369. }
  370. throw new WriterException('No Spreadsheet object assigned.');
  371. }
  372. /**
  373. * Set Spreadsheet object.
  374. *
  375. * @param Spreadsheet $spreadsheet PhpSpreadsheet object
  376. *
  377. * @return Xlsx
  378. */
  379. public function setSpreadsheet(Spreadsheet $spreadsheet)
  380. {
  381. $this->spreadSheet = $spreadsheet;
  382. return $this;
  383. }
  384. /**
  385. * Get string table.
  386. *
  387. * @return string[]
  388. */
  389. public function getStringTable()
  390. {
  391. return $this->stringTable;
  392. }
  393. /**
  394. * Get Style HashTable.
  395. *
  396. * @return HashTable
  397. */
  398. public function getStyleHashTable()
  399. {
  400. return $this->styleHashTable;
  401. }
  402. /**
  403. * Get Conditional HashTable.
  404. *
  405. * @return HashTable
  406. */
  407. public function getStylesConditionalHashTable()
  408. {
  409. return $this->stylesConditionalHashTable;
  410. }
  411. /**
  412. * Get Fill HashTable.
  413. *
  414. * @return HashTable
  415. */
  416. public function getFillHashTable()
  417. {
  418. return $this->fillHashTable;
  419. }
  420. /**
  421. * Get \PhpOffice\PhpSpreadsheet\Style\Font HashTable.
  422. *
  423. * @return HashTable
  424. */
  425. public function getFontHashTable()
  426. {
  427. return $this->fontHashTable;
  428. }
  429. /**
  430. * Get Borders HashTable.
  431. *
  432. * @return HashTable
  433. */
  434. public function getBordersHashTable()
  435. {
  436. return $this->bordersHashTable;
  437. }
  438. /**
  439. * Get NumberFormat HashTable.
  440. *
  441. * @return HashTable
  442. */
  443. public function getNumFmtHashTable()
  444. {
  445. return $this->numFmtHashTable;
  446. }
  447. /**
  448. * Get \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable.
  449. *
  450. * @return HashTable
  451. */
  452. public function getDrawingHashTable()
  453. {
  454. return $this->drawingHashTable;
  455. }
  456. /**
  457. * Get Office2003 compatibility.
  458. *
  459. * @return bool
  460. */
  461. public function getOffice2003Compatibility()
  462. {
  463. return $this->office2003compatibility;
  464. }
  465. /**
  466. * Set Office2003 compatibility.
  467. *
  468. * @param bool $pValue Office2003 compatibility?
  469. *
  470. * @return Xlsx
  471. */
  472. public function setOffice2003Compatibility($pValue)
  473. {
  474. $this->office2003compatibility = $pValue;
  475. return $this;
  476. }
  477. }