Xlsx.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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 = $chartRef2 = 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. $drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection();
  261. $drawingCount = count($drawings);
  262. if ($this->includeCharts) {
  263. $chartCount = $this->spreadSheet->getSheet($i)->getChartCount();
  264. }
  265. // Add drawing and image relationship parts
  266. if (($drawingCount > 0) || ($chartCount > 0)) {
  267. // Drawing relationships
  268. $zip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts));
  269. // Drawings
  270. $zip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $this->includeCharts));
  271. }
  272. // Add comment relationship parts
  273. if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) {
  274. // VML Comments
  275. $zip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i)));
  276. // Comments
  277. $zip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i)));
  278. }
  279. // Add header/footer relationship parts
  280. if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) {
  281. // VML Drawings
  282. $zip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i)));
  283. // VML Drawing relationships
  284. $zip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i)));
  285. // Media
  286. foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) {
  287. $zip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath()));
  288. }
  289. }
  290. }
  291. // Add media
  292. for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) {
  293. if ($this->getDrawingHashTable()->getByIndex($i) instanceof WorksheetDrawing) {
  294. $imageContents = null;
  295. $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath();
  296. if (strpos($imagePath, 'zip://') !== false) {
  297. $imagePath = substr($imagePath, 6);
  298. $imagePathSplitted = explode('#', $imagePath);
  299. $imageZip = new ZipArchive();
  300. $imageZip->open($imagePathSplitted[0]);
  301. $imageContents = $imageZip->getFromName($imagePathSplitted[1]);
  302. $imageZip->close();
  303. unset($imageZip);
  304. } else {
  305. $imageContents = file_get_contents($imagePath);
  306. }
  307. $zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
  308. } elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof MemoryDrawing) {
  309. ob_start();
  310. call_user_func(
  311. $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(),
  312. $this->getDrawingHashTable()->getByIndex($i)->getImageResource()
  313. );
  314. $imageContents = ob_get_contents();
  315. ob_end_clean();
  316. $zip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents);
  317. }
  318. }
  319. Functions::setReturnDateType($saveDateReturnType);
  320. Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
  321. // Close file
  322. if ($zip->close() === false) {
  323. throw new WriterException("Could not close zip file $pFilename.");
  324. }
  325. // If a temporary file was used, copy it to the correct file stream
  326. if ($originalFilename != $pFilename) {
  327. if (copy($pFilename, $originalFilename) === false) {
  328. throw new WriterException("Could not copy temporary zip file $pFilename to $originalFilename.");
  329. }
  330. @unlink($pFilename);
  331. }
  332. } else {
  333. throw new WriterException('PhpSpreadsheet object unassigned.');
  334. }
  335. }
  336. /**
  337. * Get Spreadsheet object.
  338. *
  339. * @throws WriterException
  340. *
  341. * @return Spreadsheet
  342. */
  343. public function getSpreadsheet()
  344. {
  345. if ($this->spreadSheet !== null) {
  346. return $this->spreadSheet;
  347. }
  348. throw new WriterException('No Spreadsheet object assigned.');
  349. }
  350. /**
  351. * Set Spreadsheet object.
  352. *
  353. * @param Spreadsheet $spreadsheet PhpSpreadsheet object
  354. *
  355. * @return Xlsx
  356. */
  357. public function setSpreadsheet(Spreadsheet $spreadsheet)
  358. {
  359. $this->spreadSheet = $spreadsheet;
  360. return $this;
  361. }
  362. /**
  363. * Get string table.
  364. *
  365. * @return string[]
  366. */
  367. public function getStringTable()
  368. {
  369. return $this->stringTable;
  370. }
  371. /**
  372. * Get Style HashTable.
  373. *
  374. * @return HashTable
  375. */
  376. public function getStyleHashTable()
  377. {
  378. return $this->styleHashTable;
  379. }
  380. /**
  381. * Get Conditional HashTable.
  382. *
  383. * @return HashTable
  384. */
  385. public function getStylesConditionalHashTable()
  386. {
  387. return $this->stylesConditionalHashTable;
  388. }
  389. /**
  390. * Get Fill HashTable.
  391. *
  392. * @return HashTable
  393. */
  394. public function getFillHashTable()
  395. {
  396. return $this->fillHashTable;
  397. }
  398. /**
  399. * Get \PhpOffice\PhpSpreadsheet\Style\Font HashTable.
  400. *
  401. * @return HashTable
  402. */
  403. public function getFontHashTable()
  404. {
  405. return $this->fontHashTable;
  406. }
  407. /**
  408. * Get Borders HashTable.
  409. *
  410. * @return HashTable
  411. */
  412. public function getBordersHashTable()
  413. {
  414. return $this->bordersHashTable;
  415. }
  416. /**
  417. * Get NumberFormat HashTable.
  418. *
  419. * @return HashTable
  420. */
  421. public function getNumFmtHashTable()
  422. {
  423. return $this->numFmtHashTable;
  424. }
  425. /**
  426. * Get \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet\BaseDrawing HashTable.
  427. *
  428. * @return HashTable
  429. */
  430. public function getDrawingHashTable()
  431. {
  432. return $this->drawingHashTable;
  433. }
  434. /**
  435. * Get Office2003 compatibility.
  436. *
  437. * @return bool
  438. */
  439. public function getOffice2003Compatibility()
  440. {
  441. return $this->office2003compatibility;
  442. }
  443. /**
  444. * Set Office2003 compatibility.
  445. *
  446. * @param bool $pValue Office2003 compatibility?
  447. *
  448. * @return Xlsx
  449. */
  450. public function setOffice2003Compatibility($pValue)
  451. {
  452. $this->office2003compatibility = $pValue;
  453. return $this;
  454. }
  455. }