i’m converting my data to excel and downloading it using PhpSpreadsheet, it gets downloaded but it won’t open on ms excel, but opens on other editors.
this is my method to convert data to excel:
public static function convertToExcel($tableData) { try { // Create a new Excel instance $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet();
// Set the Column Headers
$columnIndex = 'A';
foreach ($tableData[0] as $key => $value) {
// Make the Column Headers Bold
self::makeColumnNameBold($sheet, $columnIndex);
$sheet->setCellValue($columnIndex . '1', self::convertKeyToColumnName($key));
$columnIndex++;
}
// Set the Data Rows
$rowIndex = 2;
foreach ($tableData as $row) {
$columnIndex = 'A';
foreach ($row as $value) {
$sheet->setCellValue($columnIndex . $rowIndex, $value);
$columnIndex++;
}
$rowIndex++;
}
return ResponseFormatterHelper::formatRaw(true, 'Excel Data Converted Successfully', ApiStatusCodes::OK->value, $spreadsheet);
} catch (Exception $e) {
return ResponseFormatterHelper::formatRaw(false, ResponseMessages::INTERNAL_SERVER_ERROR->value, ApiStatusCodes::INTERNAL_SERVER_ERROR->value, null);
}
}
this is my method to download excel:
public static function downloadExcel($spreadsheet, $fileName) { try { // Clean any previous output buffer if (ob_get_length()) { ob_end_clean(); }
// Stream the Excel file to the browser
$response = new StreamedResponse(function () use ($spreadsheet) {
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
});
// Set the headers for the response
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Content-Disposition', 'attachment; filename="' . $fileName . '"');
$response->headers->set('Cache-Control', 'max-age=0');
$response->headers->set('Content-Transfer-Encoding', 'binary');
// Add CORS headers
$response->headers->set('Access-Control-Allow-Origin', '*'); // Specify frontend origin if needed
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$response->headers->set('Access-Control-Expose-Headers', 'Content-Disposition');
// Send the response to the browser
$response->send();
} catch (Exception $e) {
return ResponseFormatterHelper::formatRaw(false, ResponseMessages::INTERNAL_SERVER_ERROR->value, ApiStatusCodes::INTERNAL_SERVER_ERROR->value, null);
}
}`
I wanted it to open in Ms Excel, but it won’t. Though it opens on other editors.
3