How can PHPExcel be effectively utilized to write data from a database into an Excel spreadsheet for further processing?
To write data from a database into an Excel spreadsheet using PHPExcel, you can query the database to retrieve the data, create a new PHPExcel object, iterate over the data to populate the spreadsheet, and then save the spreadsheet to a file for further processing.
// Include PHPExcel library
require_once 'PHPExcel/Classes/PHPExcel.php';
// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Query the database to retrieve data
$query = "SELECT * FROM table";
$result = mysqli_query($conn, $query);
// Populate the spreadsheet with data
$row = 1;
while ($data = mysqli_fetch_array($result)) {
$col = 'A';
foreach ($data as $value) {
$objPHPExcel->getActiveSheet()->setCellValue($col.$row, $value);
$col++;
}
$row++;
}
// Save the spreadsheet to a file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('output.xlsx');
Related Questions
- How can PHP developers utilize the imagettfbbox function to accurately calculate text dimensions for proper alignment in image manipulation?
- How can the use of unique form names and submit buttons improve the functionality of multiple actions on a PHP page for form submissions?
- What are some resources or tutorials available online for implementing clean URLs in PHP?