diff --git a/docs/topics/reading-and-writing-to-file.md b/docs/topics/reading-and-writing-to-file.md index e1b7e3a2..a9f767aa 100644 --- a/docs/topics/reading-and-writing-to-file.md +++ b/docs/topics/reading-and-writing-to-file.md @@ -580,6 +580,18 @@ $writer->setUseBOM(true); $writer->save("05featuredemo.csv"); ``` +#### Writing CSV files with desired encoding + +It can be set to output with the encoding that can be specified by PHP's mb_convert_encoding. +This looks like the following code: + +```php +$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet); +$writer->setUseBOM(false); +$writer->setOutputEncoding('SJIS-WIN'); +$writer->save("05featuredemo.csv"); +``` + #### Decimal and thousands separators If the worksheet you are exporting contains numbers with decimal or diff --git a/src/PhpSpreadsheet/Writer/Csv.php b/src/PhpSpreadsheet/Writer/Csv.php index 74f28636..188a83a8 100644 --- a/src/PhpSpreadsheet/Writer/Csv.php +++ b/src/PhpSpreadsheet/Writer/Csv.php @@ -64,6 +64,13 @@ class Csv extends BaseWriter */ private $excelCompatibility = false; + /** + * Output encoding. + * + * @var string + */ + private $outputEncoding = ''; + /** * Create a new CSV. * @@ -296,6 +303,30 @@ class Csv extends BaseWriter return $this; } + /** + * Get output encoding. + * + * @return string + */ + public function getOutputEncoding() + { + return $this->outputEncoding; + } + + /** + * Set output encoding. + * + * @param string $pValue Output encoding + * + * @return $this + */ + public function setOutputEncoding($pValue) + { + $this->outputEncoding = $pValue; + + return $this; + } + private $enclosureRequired = true; public function setEnclosureRequired(bool $value): self @@ -347,6 +378,9 @@ class Csv extends BaseWriter $line .= $this->lineEnding; // Write to file + if ($this->outputEncoding != '') { + $line = mb_convert_encoding($line, $this->outputEncoding); + } fwrite($pFileHandle, $line); } } diff --git a/tests/PhpSpreadsheetTests/Writer/Csv/CsvOutputEncodingTest.php b/tests/PhpSpreadsheetTests/Writer/Csv/CsvOutputEncodingTest.php new file mode 100644 index 00000000..510515c3 --- /dev/null +++ b/tests/PhpSpreadsheetTests/Writer/Csv/CsvOutputEncodingTest.php @@ -0,0 +1,31 @@ +getActiveSheet(); + $sheet->setCellValue('A1', 'こんにちは!'); + $sheet->setCellValue('B1', 'Hello!'); + + $writer = new CsvWriter($spreadsheet); + + $filename = tempnam(File::sysGetTempDir(), 'phpspreadsheet-test-SJIS-win'); + $writer->setUseBOM(false); + $writer->setOutputEncoding('SJIS-win'); + $writer->save($filename); + $contents = file_get_contents($filename); + unlink($filename); + + // self::assertStringContainsString(mb_convert_encoding('こんにちは!', 'SJIS-win'), $contents); + self::assertStringContainsString("\x82\xb1\x82\xf1\x82\xc9\x82\xbf\x82\xcd\x81\x49", $contents); + } +}