In what ways can PHP be used to generate Excel files directly from SQL data, bypassing the need for web queries and potential formatting issues?

When generating Excel files directly from SQL data using PHP, one way to bypass the need for web queries and potential formatting issues is to use a library like PHPExcel. This library allows for easy creation of Excel files with data fetched from a SQL database, ensuring proper formatting and avoiding any web query complications.

<?php
require 'PHPExcel.php';

// Create new PHPExcel object
$objPHPExcel = new PHPExcel();

// Fetch data from SQL database
// Example query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Populate Excel file with data
$row = 1;
while($row_data = $result->fetch_assoc()) {
    $col = 'A';
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValue($col.$row, $value);
        $col++;
    }
    $row++;
}

// Save Excel file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('output_file.xlsx');
?>