CSV writer also use common code to open file

This commit is contained in:
Adrien Crivelli 2020-05-17 18:58:32 +09:00
parent 5f413b8a58
commit c725128a68
No known key found for this signature in database
GPG Key ID: B182FD79DC6DE92E
2 changed files with 10 additions and 18 deletions

View File

@ -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
{

View File

@ -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);
}