/** * Add a worksheet into the workbook with id $id and name $name. If $id is null the last * worksheet is replaced. If $name is empty, its default value is 'Data'. * * Currently this replaces an existing worksheet. Adding new worksheets is not yet supported * * @param ExcelWorksheet $worksheet * @param int $id * @param string $name */ public function addWorksheet(ExcelWorksheet $worksheet, $id = null, $name = 'Data') { if (is_null($id) || $id <= 0) { $lastId = 0; while ($this->getXLSX()->statName('xl/worksheets/sheet' . ($lastId + 1) . '.xml') !== false) { $lastId++; } $id = $lastId + $id; } $old = $this->getXLSX()->getFromName('xl/worksheets/sheet' . $id . '.xml'); if ($old === false) { throw new \Exception('Appending new sheets is not yet implemented: ' . $id . ', ' . $this->srcFilename . ', ' . $this->targetFilename); } else { $document = new \DOMDocument(); $document->loadXML($old); $oldSheetData = $document->getElementsByTagName('sheetData')->item(0); $worksheet->setDateTimeFormatId($this->dateTimeFormatId()); $newSheetData = $document->importNode($worksheet->getDocument()->getElementsByTagName('sheetData')->item(0), true); $oldSheetData->parentNode->replaceChild($newSheetData, $oldSheetData); $xml = $document->saveXML(); $this->getXLSX()->addFromString('xl/worksheets/sheet' . $id . '.xml', $xml); } if ($this->isAutoSaveEnabled()) { $this->save(); } return $this; }