I'm writing a php script that converts csv to xlsx.
Then problem is that source csv file has commas as decimal separator, so, in the xlsx destination file, numbers with decimals become strings.
This is my code:
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);
How can I tell the $reader to interpret commas as decimal separator?
CodePudding user response:
Since I couldn't find the solution I was looking for, I wrote this workaround:
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);
In csv file I replace ,
with .
and save it as temporary file.