What is the purpose of using PHPExcel in this scenario?
Issue: The task at hand is to generate an Excel file with data from a database using PHP. PHPExcel is a library that allows for easy creation of Excel files in PHP, making it a suitable choice for this scenario. Solution:
// Include PHPExcel library
require 'PHPExcel.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set properties for the Excel file
$objPHPExcel->getProperties()->setCreator("Your Name")
->setLastModifiedBy("Your Name")
->setTitle("Sample Excel File")
->setSubject("Sample Subject")
->setDescription("Sample Description")
->setKeywords("excel php phpexcel")
->setCategory("Sample Category");
// Add data from database to the Excel file
$sheet = $objPHPExcel->setActiveSheetIndex(0);
$sheet->setCellValue('A1', 'Column 1 Header');
$sheet->setCellValue('B1', 'Column 2 Header');
// Fetch data from database and populate the Excel file
$row = 2;
foreach($dataFromDatabase as $data) {
$sheet->setCellValue('A' . $row, $data['column1']);
$sheet->setCellValue('B' . $row, $data['column2']);
$row++;
}
// Save the Excel file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('sample.xlsx');
Related Questions
- What is the significance of using 'true' in the json_decode function in PHP when dealing with JSON objects?
- What are some potential pitfalls when using RecursiveDirectoryIterator in PHP to search for specific files?
- How can you use the SELECT statement in PHP to retrieve a specific field from a database?