0

me habian ayudado a mejorar el codigo de una exportacion de php a excel ahora mi duda es ya que los tengo me sale un formato diferente

maso menos como la siguiente imagen me aparece

introducir la descripción de la imagen aquí

entonces lo que necesito es que me aparescan bien los campos de en cada una de las columnas

para que se pueda ver bien dentro del excel

<?php
    
    $mysqli=new mysqli('127.0.0.1:4473','root' , '', 'convenios'); //servidor, usuario de base de datos, contraseña del usuario, nombre de base de datos
    
    if(mysqli_connect_errno()){
        echo 'Conexion Fallida : ', mysqli_connect_error();
        exit();
    }
    

    //Incluimos librería y archivo de conexión
    require 'PHPExcel/Classes/PHPExcel.php';
    
    //Consulta
    $sql = "SELECT usuario, fecha_soli,cuenta, fecha_prom, nombre_tt,sdo_total, mont_pagar,de_desc, fecha_pago,tipo_solicitud,
    actualizado_a, estatus FROM convenio order by  actualizado_a ASC LIMIT 50" ;
    $resultado = $mysqli->query($sql);
    $fila = 7; //Establecemos en que fila inciara a imprimir los datos
    
    
    //Objeto de PHPExcel
    $objPHPExcel  = new PHPExcel();
    
    //Propiedades de Documento
    $objPHPExcel->getProperties()->setCreator("ING.Roberto Mendoza")->setDescription("Reporte de Convenios");
    
    //Establecemos la pestaña activa y nombre a la pestaña
    $objPHPExcel->setActiveSheetIndex(0);
    $objPHPExcel->getActiveSheet()->setTitle("convenio");
    
    $estiloTituloReporte = array(
    'font' => array(
    'name'      => 'Arial',
    'bold'      => true,
    'italic'    => false,
    'strike'    => false,
    'size' =>13
    ),
    'fill' => array(
    'type'  => PHPExcel_Style_Fill::FILL_SOLID
    ),
    'borders' => array(
    'allborders' => array(
    'style' => PHPExcel_Style_Border::BORDER_NONE
    )
    ),
    'alignment' => array(
    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
    )
    );
    
    $estiloTituloColumnas = array(
    'font' => array(
    'name'  => 'Arial',
    'bold'  => true,
    'size' =>10,
    'color' => array(
    'rgb' => 'FFFFFF'
    )
    ),
    'fill' => array(
    'type' => PHPExcel_Style_Fill::FILL_SOLID,
    'color' => array('rgb' => '538DD5')
    ),
    'borders' => array(
    'allborders' => array(
    'style' => PHPExcel_Style_Border::BORDER_THIN
    )
    ),
    'alignment' =>  array(
    'horizontal'=> PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    'vertical'  => PHPExcel_Style_Alignment::VERTICAL_CENTER
    )
    );
    
    $estiloInformacion = new PHPExcel_Style();
    $estiloInformacion->applyFromArray( array(
    'font' => array(
    'name'  => 'Arial',
    'color' => array(
    'rgb' => '000000'
    )
    ),
    'fill' => array(
    'type'  => PHPExcel_Style_Fill::FILL_SOLID
    ),
    'borders' => array(
    'allborders' => array(
    'style' => PHPExcel_Style_Border::BORDER_THIN
    )
    ),
    'alignment' =>  array(
    'horizontal'=> PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    'vertical'  => PHPExcel_Style_Alignment::VERTICAL_CENTER
    )
    ));
    
    $objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray($estiloTituloReporte);
    
    $objPHPExcel->getActiveSheet()->setCellValue('A1', 'REPORTE DE CONVENIOS');
    
    $objPHPExcel->getActiveSheet()->setCellValue('A6', 'usuario');
    $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
    $objPHPExcel->getActiveSheet()->setCellValue('B6', 'FECHA SOLICITUD');
    $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(10);
    $objPHPExcel->getActiveSheet()->setCellValue('C6', 'CUENTA');
    $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
    $objPHPExcel->getActiveSheet()->setCellValue('D6', 'FECHA PROMESA');
    $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
    $objPHPExcel->getActiveSheet()->setCellValue('E6', 'NOMBRE DE TITUTAR');
    $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
    $objPHPExcel->getActiveSheet()->setCellValue('F6', 'SALDO TOTAL');
    $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(10);
    $objPHPExcel->getActiveSheet()->setCellValue('G6', 'MONTO A PAGAR');
    $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);
    $objPHPExcel->getActiveSheet()->setCellValue('H6', '% DE DESCUENTO');
    $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(10);
    $objPHPExcel->getActiveSheet()->setCellValue('I6', 'FECHA DE PAGO');
    $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(10);
    $objPHPExcel->getActiveSheet()->setCellValue('J6', 'TIPO DE SOLICITUD');
    $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(10);
    $objPHPExcel->getActiveSheet()->setCellValue('K6', 'ULTI. ACTUALIZACION');
    $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(10);
    $objPHPExcel->getActiveSheet()->setCellValue('L6', 'STATUS');
    //Recorremos los resultados de la consulta y los imprimimos
    while($rows = $resultado->fetch_assoc()){

        $objPHPExcel->getActiveSheet()->setCellValue('A'.$fila, $rows['usuario']);
        $objPHPExcel->getActiveSheet()->setCellValue('B'.$fila, $rows['fecha_soli']);
        $objPHPExcel->getActiveSheet()->setCellValue('C'.$fila, $rows['cuenta']);
        $objPHPExcel->getActiveSheet()->setCellValue('D'.$fila, $rows['fecha_prom']);
        $objPHPExcel->getActiveSheet()->setCellValue('E'.$fila, $rows['nombre_tt']);
        $objPHPExcel->getActiveSheet()->setCellValue('F'.$fila, $rows['sdo_total']);
        $objPHPExcel->getActiveSheet()->setCellValue('G'.$fila, $rows['mont_pagar']);
        $objPHPExcel->getActiveSheet()->setCellValue('H'.$fila, $rows['de_desc']);
        $objPHPExcel->getActiveSheet()->setCellValue('I'.$fila, $rows['fecha_pago']);
        $objPHPExcel->getActiveSheet()->setCellValue('J'.$fila, $rows['tipo_solicitud']);
        $objPHPExcel->getActiveSheet()->setCellValue('K'.$fila, $rows['actualizado_a']);
        $objPHPExcel->getActiveSheet()->setCellValue('L'.$fila, $rows['estatus']);
        
        $fila++; //Sumamos 1 para pasar a la siguiente fila
    }
    
    $fila = $fila-1;
    
    
    
    
    
    // incluir gráfico
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Disposition: attachment;filename="Solicitud convenios.xls"');
header('Cache-Control: max-age=0');

$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);

$objWriter->save('php://output');

exit;
?>

lo que busco es que se vea con el siguiente formato introducir la descripción de la imagen aquí

para que quede bien el reporte mencionaban que phpexcel ya es obsoleto pero phpsheet necesito instalar laravel y aqui tengo phppuro

gracias!!!!!

1 respuesta 1

0

te mando el ejemplo del mio, me funciona correctamente

<?php

use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Font;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

require_once '../src/Bootstrap.php';

$helper = new Sample();
if ($helper->isCli()) {
    $helper->log('This example should only be run from a Web Browser' . PHP_EOL);

    return;
}
// Create new Spreadsheet object
$spreadsheet = new Spreadsheet();

// Set document properties
$spreadsheet->getProperties()->setCreator('Maarten Balliauw')
    ->setLastModifiedBy('Maarten Balliauw')
    ->setTitle('Office 2007 XLSX Test Document')
    ->setSubject('Office 2007 XLSX Test Document')
    ->setDescription('Test document for Office 2007 XLSX, generated using PHP classes.')
    ->setKeywords('office 2007 openxml php')
    ->setCategory('Test result file');

// Add some data
$spreadsheet->setActiveSheetIndex(0)
->setCellValue('A1', 'Abrev.')
->setCellValue('B1', 'Curso')
->setCellValue('C1', 'Fecha')
->setCellValue('D1', 'Fecha limite')
->setCellValue('E1', 'Estado')
->setCellValue('F1', 'fecha entrega');

include 'database.php';

$pdo = Database::connect();
$sql = 'SELECT fecha, cursoabrev, fechaup, idalumno, cursoname FROM eventos left join curso ON eventos.idcurso = curso.idcurso left join eventos_alumnos ON eventos.ideventos = eventos_alumnos.ideventos';
    $i=2;
foreach ($pdo->query($sql) as $row) {
$cursoabrev = $row['cursoabrev'];
$cursoname = $row['cursoname'];
$fechaprin = strtotime($row['fecha']);
$fechaprin = (date ("d-m-Y", $fechaprin));
$fechalimi = strtotime($row['fecha'])+(86400*2);
$fechalimi = (date ("d-m-Y", $fechalimi));
if(!is_null($row['idalumno'])){ $estado="entregado"; }
else { $estado="pendiente"; };
if(!is_null($row['fechaup'])){$fechaup = date("d-m-Y" ,strtotime($row['fechaup']));}
else { $fechaup = " ";};

    $spreadsheet->setActiveSheetIndex(0)
    ->setCellValue("A$i", $cursoabrev)
    ->setCellValue("B$i", $cursoname)
    ->setCellValue("C$i", $fechaprin)
    ->setCellValue("D$i", $fechalimi)
    ->setCellValue("E$i", $estado)
    ->setCellValue("F$i", $fechaup);

    $i++;

}
Database::disconnect();
$i = $i-1;

// Set column widths
//$helper->log('Set column widths');
$spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$spreadsheet->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
$spreadsheet->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
$spreadsheet->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
$spreadsheet->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);


// Set thin black border outline around column
//$helper->log('Set thin black border outline around column');
$styleThinBlackBorderOutline = [
    'borders' => [
        'outline' => [
            'borderStyle' => Border::BORDER_THIN,
            'color' => ['argb' => 'FF000000'],
        ],
    ],
];
$spreadsheet->getActiveSheet()->getStyle('A2:F'.$i)->applyFromArray($styleThinBlackBorderOutline);

// Set fills
//$helper->log('Set fills');
$spreadsheet->getActiveSheet()->getStyle('A1:F1')->getFill()->setFillType(Fill::FILL_SOLID);
$spreadsheet->getActiveSheet()->getStyle('A1:F1')->getFill()->getStartColor()->setARGB('FFa1ecbf');


// Set fonts
//$helper->log('Set fonts');
//$spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setName('Candara');
$spreadsheet->getActiveSheet()->getStyle('A1:F1')->getFont()->setSize(12);
$spreadsheet->getActiveSheet()->getStyle('A1:F1')->getFont()->setBold(true);


// Rename worksheet
$spreadsheet->getActiveSheet()->setTitle('Listado_tareas');

// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$spreadsheet->setActiveSheetIndex(0);

// Redirect output to a client’s web browser (Xlsx)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="listado_tareas.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0

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

3
  • Por favor lee Cómo responder, mas que solo publicarle el código al OP, en el sitio se espera una respuesta mas completa, por ejemplo ¿cómo integra esto a su proyecto?, ya que como notas los comentarios de tu script están en inglés y aquí lo ideal es en español
    – BetaM
    el 25 jun. 2020 a las 18:31
  • El OP requiere de una respuesta más elaborada con una explicación, por favor edita tu respuesta y hazla más entendible.
    – user166844
    el 25 jun. 2020 a las 18:49
  • lo adecue a mi tabla pero me salio error
    – user179236
    el 25 jun. 2020 a las 19:17

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.