PHPSpreadSheet 以逗号作为小数点分隔符转换 csv

PHPSpreadSheet convert csv with comma as decimal separator

我正在编写 php 将 csv 转换为 xlsx 的脚本。

然后问题是源 csv 文件使用逗号作为小数点分隔符,因此,在 xlsx 目标文件中,带小数点的数字变成字符串。

这是我的代码:

require __DIR__ . '/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();

/* Set CSV parsing options */

$reader->setDelimiter(';');
$reader->setEnclosure('"');
$reader->setSheetIndex(0);

/* Load a CSV file and save as a XLS */

$spreadsheet = $reader->load('csv/test.csv');
$writer = new Xlsx($spreadsheet);
$writer->save('test.xlsx');

$spreadsheet->disconnectWorksheets();
unset($spreadsheet);

如何让 $reader 将逗号解释为小数点分隔符?

由于找不到我正在寻找的解决方案,我写了这个解决方法:

require __DIR__ . '/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();

$reader->setDelimiter(';');
$reader->setEnclosure('"');
$reader->setSheetIndex(0);


$content = file_get_contents('csv/test.csv');
$content = str_replace(',','.',$content);
$tmpfilename = 'cache/test.csv';
file_put_contents($tmpfilename, $content);

$spreadsheet = $reader->load($tmpfilename);
unlink($tmpfilename);

$writer = new Xlsx($spreadsheet);
$writer->save('test.xlsx');

$spreadsheet->disconnectWorksheets();
unset($spreadsheet);

在 csv 文件中,我将 , 替换为 . 并将其保存为临时文件。