Files
citrus-cms/app/Functions/csv_to_xlsx.php
T
2026-04-28 21:14:25 +03:00

51 lines
1.3 KiB
PHP

<?php
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
function csv_to_xlsx($csvFilePath, $outputFilePath, $delimiter= "\t")
{
try {
// Create a new Spreadsheet object
$spreadsheet = new Spreadsheet();
// Get the active sheet
$sheet = $spreadsheet->getActiveSheet();
// Open the CSV file
$file = fopen($csvFilePath, 'r');
if (!$file) {
throw new \Exception("Cannot open CSV file.");
}
$rowIndex = 1;
// Read each row and add it to the spreadsheet
while (($row = fgetcsv($file, 0, $delimiter)) !== false) {
$colIndex = 'A';
foreach ($row as $cell) {
// Veriyi hücreye yaz
// if($cell == "NULL") $cell = "";
$sheet->setCellValue($colIndex . $rowIndex, $cell);
$colIndex++;
}
$rowIndex++;
}
fclose($file);
// Write to XLSX file
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save($outputFilePath);
return $outputFilePath;
} catch (\Exception $e) {
$result = [];
$result['error'] = "Error: " . $e->getMessage();
return $result;
}
}
?>