Merge pull request #1869 from AkiraPenguin/master

Add "outputEncoding" property to Writer/Csv.php
This commit is contained in:
oleibman 2021-04-06 09:01:52 -07:00 committed by GitHub
commit 37ebc99a5a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 77 additions and 0 deletions

View File

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

View File

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

View File

@ -0,0 +1,31 @@
<?php
namespace PhpOffice\PhpSpreadsheetTests\Writer\Csv;
use PhpOffice\PhpSpreadsheet\Shared\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Csv as CsvWriter;
use PhpOffice\PhpSpreadsheetTests\Functional;
class CsvOutputEncodingTest extends Functional\AbstractFunctional
{
public function testEncoding(): void
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->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);
}
}