How can PHPExcel be utilized as an alternative solution for exporting data to Excel in PHP?
When needing to export data to Excel in PHP, PHPExcel can be utilized as an alternative solution. PHPExcel is a library that allows for easy creation of Excel files with various formatting options. By using PHPExcel, developers can generate Excel files containing data from databases, arrays, or any other data source, making it a versatile tool for exporting data in PHP.
// Include PHPExcel library
require_once 'PHPExcel/PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Add data to the Excel file
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B1', 'World');
// Set headers for Excel file
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="exported_data.xlsx"');
header('Cache-Control: max-age=0');
// Save Excel file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');