From 811b7d73697eab7894f2243fac38b2c218ef64e1 Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 6 Sep 2024 12:34:01 -0600 Subject: [PATCH] Action de Excel de Puestos --- action/action_puestos_excel.php | 74 +++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 action/action_puestos_excel.php diff --git a/action/action_puestos_excel.php b/action/action_puestos_excel.php new file mode 100644 index 0000000..45d18c5 --- /dev/null +++ b/action/action_puestos_excel.php @@ -0,0 +1,74 @@ +print_to_log('Genera excel de materias por puesto'); + +use PhpOffice\PhpSpreadsheet\Spreadsheet; +use PhpOffice\PhpSpreadsheet\IOFactory; + +// Create the Spreadsheet +$spreadsheet = new Spreadsheet(); + +// Get data for each 'puesto' +$puestos = $db->orderBy('nombre')->where('facultad_id', $user->facultad['facultad_id'])->get('puesto', columns: ['nombre', 'puesto_id']); + +$sheetIndex = 0; // To track and switch between sheets + +foreach ($puestos as $puesto) { + // Create a new worksheet for each 'puesto' + if ($sheetIndex == 0) { + // Use the first default sheet + $sheet = $spreadsheet->getActiveSheet(); + $sheet->setTitle($puesto['nombre']); // Name the first sheet + } else { + $sheet = $spreadsheet->createSheet(); // Create new sheet + $sheet->setTitle($puesto['nombre']); // Set sheet title to puesto name + } + + // Get associated materias for current puesto + $materias = $db + ->join('materia m', 'm.materia_id = pm.materia_id') + ->orderBy('materia_nombre') + ->where('puesto_id', $puesto['puesto_id']) + ->get('puesto_materia pm', columns: ['clave_materia', 'materia_nombre']); + + // Add header row for each 'materia' table + $sheet->setCellValue('A1', 'Clave Materia'); + $sheet->setCellValue('B1', 'Materia Nombre'); + + // Set some styling for headers + $sheet->getStyle('A1:B1')->getFont()->setBold(true); + $sheet->getStyle('A1:B1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER); + + // Start populating from the second row + $row = 2; + + // Populate the sheet with materias data + foreach ($materias as $materia) { + $sheet->setCellValue("A$row", $materia['clave_materia']); + $sheet->setCellValue("B$row", $materia['materia_nombre']); + $row++; + } + + // Auto-size columns + foreach (range('A', 'B') as $column) { + $sheet->getColumnDimension($column)->setAutoSize(true); + } + + // Move to the next sheet index + $sheetIndex++; +} + +// Set the first sheet as active when the Excel file is opened +$spreadsheet->setActiveSheetIndex(0); + +// Output the file for download +header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); +header('Content-Disposition: attachment;filename="materias_por_puesto.xlsx"'); +header('Cache-Control: max-age=0'); + +$writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); +$writer->save('php://output');