diff --git a/src/PhpSpreadsheet/Writer/BaseWriter.php b/src/PhpSpreadsheet/Writer/BaseWriter.php index dc7a0431..afda5c43 100644 --- a/src/PhpSpreadsheet/Writer/BaseWriter.php +++ b/src/PhpSpreadsheet/Writer/BaseWriter.php @@ -108,9 +108,9 @@ abstract class BaseWriter implements IWriter return; } - $fileHandle = fopen($filename, 'wb+'); + $fileHandle = $filename ? fopen($filename, 'wb+') : false; if ($fileHandle === false) { - throw new Exception('Could not open file ' . $filename . ' for writing.'); + throw new Exception('Could not open file "' . $filename . '" for writing.'); } $this->fileHandle = $fileHandle; @@ -118,7 +118,7 @@ abstract class BaseWriter implements IWriter } /** - * Close file handle only we opened it ourselves. + * Close file handle only if we opened it ourselves. */ protected function maybeCloseFileHandle(): void { diff --git a/src/PhpSpreadsheet/Writer/Csv.php b/src/PhpSpreadsheet/Writer/Csv.php index cabfe450..4344a5bd 100644 --- a/src/PhpSpreadsheet/Writer/Csv.php +++ b/src/PhpSpreadsheet/Writer/Csv.php @@ -4,7 +4,6 @@ namespace PhpOffice\PhpSpreadsheet\Writer; use PhpOffice\PhpSpreadsheet\Calculation\Calculation; use PhpOffice\PhpSpreadsheet\Spreadsheet; -use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException; class Csv extends BaseWriter { @@ -91,17 +90,7 @@ class Csv extends BaseWriter Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE); // Open file - if (is_resource($pFilename)) { - $fileHandle = $pFilename; - } elseif (!$pFilename) { - $fileHandle = false; - } else { - $fileHandle = fopen($pFilename, 'wb+'); - } - - if ($fileHandle === false) { - throw new WriterException("Could not open file $pFilename for writing."); - } + $this->openFileHandle($pFilename); if ($this->excelCompatibility) { $this->setUseBOM(true); // Enforce UTF-8 BOM Header @@ -110,13 +99,15 @@ class Csv extends BaseWriter $this->setDelimiter(';'); // Set delimiter to a semi-colon $this->setLineEnding("\r\n"); } + if ($this->useBOM) { // Write the UTF-8 BOM code if required - fwrite($fileHandle, "\xEF\xBB\xBF"); + fwrite($this->fileHandle, "\xEF\xBB\xBF"); } + if ($this->includeSeparatorLine) { // Write the separator line if required - fwrite($fileHandle, 'sep=' . $this->getDelimiter() . $this->lineEnding); + fwrite($this->fileHandle, 'sep=' . $this->getDelimiter() . $this->lineEnding); } // Identify the range that we need to extract from the worksheet @@ -128,9 +119,10 @@ class Csv extends BaseWriter // Convert the row to an array... $cellsArray = $sheet->rangeToArray('A' . $row . ':' . $maxCol . $row, '', $this->preCalculateFormulas); // ... and write to the file - $this->writeLine($fileHandle, $cellsArray[0]); + $this->writeLine($this->fileHandle, $cellsArray[0]); } + $this->maybeCloseFileHandle(); Calculation::setArrayReturnType($saveArrayReturnType); Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); }