MySQL в XLS с использованием PHP?


Как я могу создать документ .XLS из таблицы MySQL с помощью PHP?

Я перепробовал почти все, но безуспешно.

В принципе, мне нужно взять данные формы и ввести их в базу данных, что я и сделал, а затем мне нужно извлечь эти данные таблицы и проанализировать их в файле Microsoft Excel, который необходимо автоматически сохранить на веб-сервере.

    <?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() );

// 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();
?>

Я просто не могу понять, как интегрировать fwrite во все это, чтобы записать сгенерированные данные в файл .xls, как бы я это сделал?

Мне нужно, чтобы это работало довольно срочно, поэтому любая помощь будет очень признательна. Спасибо, ребята.

Author: Odyss3us, 2010-03-22

5 answers

Если у вас есть какой-то интерфейс для вашей базы данных (например, phpMyAdmin или SQLyog), вы можете экспортировать таблицу (или результат любого запроса SELECT) в CSV и открыть ее в Excel.

РЕДАКТИРОВАТЬ после комментариев: Однажды я создал XLS. Это было немного по-другому, но то, что я сделал, было помещено в начало моего PHP (до того, как был сгенерирован какой-либо вывод):

header("Content-type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=\"name.xls\"");

И в остальной части сценария я просто повторил таблицу (таблица, tr, td... и т. Д.) Выполнение этого сценария даст пользователю скачать. Я думаю, что есть несколько различных вариантов атрибута "Расположение содержимого" (возможно, есть один, который позволяет скрипту сохранять файл).

 1
Author: rael_kid, 2010-03-22 09:08:19

Я часто использовал PEAR Spreadsheet_Excel_Writer в своих проектах, и он хорошо работает. Однако он генерирует файлы уровня Excel 5.0, поэтому для ваших целей этого может быть недостаточно, если вам нужно что-то более продвинутое, но он будет генерировать собственный файл .xls, а не просто файл.csv, маскирующийся под .xls.

 1
Author: Marc B, 2010-03-22 15:08:09

Если я правильно понял, сценарий, который вы опубликовали, работает правильно и создает правильный файл xls, и вы хотите просто сохранить вывод, посмотрите на http://php.net/manual/en/book.outcontrol.php . С помощью ob_get_clean() вы можете получить созданный файл xls и записать его куда-нибудь на сервер.

Возможно, вы могли бы рассмотреть и другие варианты, такие как сохранение ваших данных в каком-либо другом формате, который может читать Excel (.csv, возможно, он также может читать некоторые таблицы html/xml).

 0
Author: Krab, 2010-03-22 09:07:19

Я попробовал это с помощью ob_get_clean(), но это не сработало, вот код, над которым я сейчас работаю:

<?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() {
    $output = pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
    return;
}

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

// this will write text in the cell you specify
function xlsWriteLabel($Row, $Col, $Value ) {
    $L = strlen($Value);
    $output .= pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    $file = fopen("exported.xls","w");
    fwrite($file, "$output");
    fclose($file);
    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();



?>

Я даже не знаю, имеет ли это смысл, но я добавил fwrite в функции XLSBOF, XLSEOF и xlsWriteLabel, чтобы попытаться записать данные в exported.xls файл, может ли это так работать?

 0
Author: Odyss3us, 2010-03-22 12:40:01

Все работает, вот где находится ответ. :-)

Сохранение файла .xls с помощью fwrite

 0
Author: Odyss3us, 2017-05-23 12:01:12