I’m having trouble with an Excel file generation and download system. I need to generate an .xlsx file from the data in a table, and then have the user download it. However, I can’t manage to save the file. Do you know why?
There is my html and my js script:
<form action="demandereparations_export.php" method="post">
<input type="hidden" name="NomFichier" value="<?php echo 'DemRep'.date('Y-m-d_His').'.xlsx'?>"/>
<div class="filtre">
<?php echo isset($NomFichier) ? 'NomFichier est défini' : 'NomFichier n'est pas défini'; ?>
<?php if(!empty($NomFichier)) { ?>
<a href="./components/com_teamsmart/views/dashboard/tmpl/<?php echo $NomFichier; ?>" download="<?php echo $NomFichier; ?>" id="downloadLink" class="btn btn-success" >
En cours
</a>
<?php }?>
</div>
</form>
</div>
<script type="text/javascript">
console.log('Script démarré');
window.addEventListener('DOMContentLoaded', function() {
var downloadLink = document.getElementById('downloadLink');
console.log(downloadLink);
if (downloadLink) {
downloadLink.addEventListener('click', function(event) {
console.log('Téléchargement')
});
} else {
console.log('Bouton introuvable');
}
})
</script>
Then there’s my export file:
<script src="demandereparations.php"></script>
<?php
require 'vendor/autoload.php';
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;
$filename = 'DemRep'.date('Y-m-d_His').'.xlsx';
$spreadsheet = new Spreadsheet();
$spreadsheet->getDefaultStyle()->getFont()->setName('Arial Nova');
$spreadsheet->getDefaultStyle()->getFont()->setSize(9);
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Employé.e');
$sheet->setCellValue('B1', 'Date');
$sheet->setCellValue('C1', 'N° TRPO');
$sheet->setCellValue('D1', 'N°SR');
$sheet->setCellValue('E1', 'Statut');
// $demandereparations = $this->demandereparations;
// echo $demandereparations;
// $rowIndex = 2;
// foreach ($demandereparations as $demande) {
// if (in_array($demande['user_id'], $employes_ids)) {
// $sheet->setCellValue('A' . $rowIndex, $demande['user_name']);
// $sheet->setCellValue('B' . $rowIndex, $demande['date']);
// $trpo = array_filter($demande['fields'], function($v) { return $v['alias'] == 'trpo'; });
// $sr = array_filter($demande['fields'], function($v) { return $v['alias'] == 'sr'; });
// $sheet->setCellValue('C' . $rowIndex, reset($trpo)['reponse']);
// $sheet->setCellValue('D' . $rowIndex, reset($sr)['reponse']);
// $statut = ($demande['statut'] == -1) ? "Non valide" : (($demande['statut'] == 0) ? "En attente" : (($demande['statut'] == 1) ? "En cours" : "Traitée"));
// $sheet->setCellValue('E' . $rowIndex, $statut);
// $rowIndex++;
// }
// }
$writer = new Xlsx($spreadsheet);
$writer->save('./components/com_teamsmart/views/dashboard/tmpl/' . $filename);
?>