1

I am generating an Excel file with an sql query, this so that it shows me all the records, the problem is that it works correctly locally, the excel is generated and downloaded, but when uploading it to the server it sends me to the file where the code is and on screen it shows me strange symbols

This is my code from my file to generate the excel and download it.

 <?php
// Declaramos la librería
require __DIR__ . "/../vendor/autoload.php";
// BD
require "../conexion/dbconect.php";

use PhpOffice\PhpSpreadsheet\{Spreadsheet, IOFactory};

$query = "SELECT * FROM siacc_usuarios";
$resultado = $con->query($query);

$excel = new Spreadsheet();

$activeSheet = $excel->getActiveSheet();

//set default font
$excel->getDefaultStyle()
    ->getFont()
    ->setName('Arial')
    ->setSize(10);

$excel->getActiveSheet()->getStyle('A1:V1')->getFont()->setBold(true);       

$activeSheet->setTitle("usuarios");
 
$activeSheet->getColumnDimension('A')->setwidth(10);  
$activeSheet->setCellValue('A1', 'ID Usuario');
$activeSheet->getColumnDimension('B')->setwidth(10);  
$activeSheet->setCellValue('B1', 'CEC');
$activeSheet->getColumnDimension('C')->setwidth(80);  
$activeSheet->setCellValue('C1', 'Adscripcion');
$activeSheet->getColumnDimension('D')->setwidth(20);  
$activeSheet->setCellValue('D1', 'Numero Empleado');
$activeSheet->getColumnDimension('E')->setwidth(20);  
$activeSheet->setCellValue('E1', 'Apellido Paterno');



    $i = 2;

    while($row = $resultado->fetch_assoc()) {
        $activeSheet->setCellValue('A'.$i , $row['id_usuario']);
        $activeSheet->setCellValue('B'.$i , $row['cec']);
        $activeSheet->setCellValue('C'.$i , $row['adscripcion']);
        $activeSheet->setCellValue('D'.$i , $row['emp']);
        $activeSheet->setCellValue('E'.$i , $row['ape_pat']);
    
        $i++;
    }

  
$filename = 'usuarios.xlsx';
  
// redirect output to client browser
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');

$writer = IOFactory::createWriter($excel, 'Xlsx');
ob_end_clean();
$writer->save('php://output');

This is what it shows me on screen:

enter image description here

  • That looks like the headers had not actually been set, so that the browser thinks this was a normal HTML document. Have you enabled proper PHP error reporting on the server, and checked the logs? – CBroe Dec 03 '21 at 08:38

0 Answers0