Pregunta

Tengo que crear un script que lleva una tabla de MySQL, y exporta en formato .xls, y luego guarda el archivo en una carpeta especificada en la red de acogida.

Lo tengo trabajo, pero ahora parece que no puede conseguirlo para guardar automáticamente el archivo en la ubicación sin preguntar al usuario.

Tiene que correr todos los días a una hora determinada, por lo que puede guardar los días anteriores conduce a un archivo .xls en la red de acogida.

Este es el código:

<?php

// DB TABLE Exporter
//
// How to use:
//
// Place this file in a safe place, edit the info just below here
// browse to the file, enjoy!

// CHANGE THIS STUFF FOR WHAT YOU NEED TO DO

     $dbhost  = "-";
     $dbuser  = "-";
     $dbpass  = "-";
     $dbname  = "-";
     $dbtable = "-";

// END CHANGING STUFF

$cdate = date("Y-m-d"); // get current date


// first thing that we are going to do is make some functions for writing out
// and excel file. These functions do some hex writing and to be honest I got 
// them from some where else but hey it works so I am not going to question it 
// just reuse


// This one makes the beginning of the xls file
function xlsBOF() {
    echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
    return;
}

// This one makes the end of the xls file
function xlsEOF() {
    echo pack("ss", 0x0A, 0x00);
    return;
}

// this will write text in the cell you specify
function xlsWriteLabel($Row, $Col, $Value ) {
    $L = strlen($Value);
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    echo $Value;
    return;
}



// make the connection an DB query
$dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
mysql_select_db( $dbname );
$q = "SELECT * FROM ".$dbtable." WHERE date ='$cdate'";
$qr = mysql_query( $q ) or die( mysql_error() );


// Ok now we are going to send some headers so that this 
// thing that we are going make comes out of browser
// as an xls file.
// 
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");

//this line is important its makes the file name
header("Content-Disposition: attachment;filename=export_".$dbtable.".xls ");

header("Content-Transfer-Encoding: binary ");

// start the file
xlsBOF();

// these will be used for keeping things in order.
$col = 0;
$row = 0;

// This tells us that we are on the first row
$first = true;

while( $qrow = mysql_fetch_assoc( $qr ) )
{
    // Ok we are on the first row
    // lets make some headers of sorts
    if( $first )
    {
        foreach( $qrow as $k => $v )
        {
            // take the key and make label
            // make it uppper case and replace _ with ' '
            xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
            $col++;
        }

        // prepare for the first real data row
        $col = 0;
        $row++;
        $first = false;
    }

    // go through the data
    foreach( $qrow as $k => $v )
    {
        // write it out
        xlsWriteLabel( $row, $col, $v );
        $col++;
    }
    // reset col and goto next row
    $col = 0;
    $row++;
}

xlsEOF();
exit();
?>

He intentado utilizar, fwrite de lograr esto, pero no parecía ir muy bien, me quita la información del encabezado también, pero nada funcionó.

Este es el código original, ya que me pareció, cualquier ayuda sería muy apreciada. : -)

Gracias de antemano. : -)

¿Fue útil?

Solución

En primer lugar, ya que está guardando este disco a través de cron se debe eliminar toda la cabecera () llama como usted sospechaba. Con el fin de volver a escribir tan poco de su código como sea posible, yo recomendaría el uso de búferes de salida ( http://www.php.net/manual/en/ref.outcontrol.php ). Para lograr esto, realizar una llamada a ob_start () antes de su salida del archivo comienza:

ob_start();
// start the file
xlsBOF();

Y después de sus extremos de salida, cerrar el búfer de salida, capturar su contenido y escribirlas en un archivo:

xlsEOF();
// $filename should be set to some writeable location
file_put_contents($filename, ob_get_clean());

Otros consejos

Este es el código final, funciona como un encanto.

<?php

    // DB TABLE Exporter
    //
    // How to use:
    //
    // Place this file in a safe place, edit the info just below here
    // browse to the file, enjoy!

    // CHANGE THIS STUFF FOR WHAT YOU NEED TO DO
         $cdate = date("Y-m-d");
         $dbhost  = "-";
         $dbuser  = "-";
         $dbpass  = "-";
         $dbname  = "-";
         $dbtable = "-";
         $filename = "exported_on_$cdate.xls";

    // END CHANGING STUFF


    // first thing that we are going to do is make some functions for writing out
    // and excel file. These functions do some hex writing and to be honest I got 
    // them from some where else but hey it works so I am not going to question it 
    // just reuse


    // This one makes the beginning of the xls file
    function xlsBOF() {
        echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
        return;
    }

    // This one makes the end of the xls file
    function xlsEOF() {
        echo pack("ss", 0x0A, 0x00);
        return;
    }

    // this will write text in the cell you specify
    function xlsWriteLabel($Row, $Col, $Value ) {
        $L = strlen($Value);
        echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
        echo $Value;
        return;
    }



    // make the connection an DB query
    $dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
    mysql_select_db( $dbname );
    $q = "SELECT * FROM ".$dbtable." WHERE date ='$cdate'";
    $qr = mysql_query( $q ) or die( mysql_error() );

    //start the object
     ob_start();

    // start the file
    xlsBOF();

    // these will be used for keeping things in order.
    $col = 0;
    $row = 0;

    // This tells us that we are on the first row
    $first = true;

    while( $qrow = mysql_fetch_assoc( $qr ) )
    {
        // Ok we are on the first row
        // lets make some headers of sorts
        if( $first )
        {
            foreach( $qrow as $k => $v )
            {
                // take the key and make label
                // make it uppper case and replace _ with ' '
                xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
                $col++;
            }

            // prepare for the first real data row
            $col = 0;
            $row++;
            $first = false;
        }

        // go through the data
        foreach( $qrow as $k => $v )
        {

            // write it out
            xlsWriteLabel( $row, $col, $v );
            $col++;
        }

        // reset col and goto next row
        $col = 0;
        $row++;

    }

    xlsEOF();

    //write the contents of the object to a file
    file_put_contents($filename, ob_get_clean());

    ?>

Gracias por todos los tipos de ayuda !!!

¿Se XLS o formato de archivo XSL? Me tiene confundido.

  • supongo que es XLS:

En primer lugar: ¿necesita para establecer estilos de fuente, utilizar múltiples pestañas, las fórmulas de uso? Si así que intenta ir a una biblioteca de Excel como phpwriteexcel.

De lo contrario, un archivo csv simple es suficiente (valores separados por comas, creado muy fácilmente de las matrices, leer perfectamente con Excel y otros programas de hojas de cálculo).

A continuación, guardarlo automáticamente sin preguntar:. Ir para una tarea de trabajo / cron en planificación, llamando a su script

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top