如何使用PHP從mySQL表創建一個.XLS文檔?mySQL to XLS using PHP?
我已經嘗試了幾乎所有的東西,沒有成功。
基本上,我需要採取表單數據,並將其輸入到我已經完成的數據庫中,然後我需要檢索該表數據並將其解析爲Microsoft Excel文件,該文件需要自動保存到Web服務器。
<?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文件,我將如何去這樣做?
我需要得到這個相當緊迫的工作,所以任何幫助將不勝感激。 Thanx傢伙。
它需要實現自動化,該腳本將通過cron作業每天在指定時間運行,我只需要弄清楚如何讓腳本保存生成的XLS數據到自動文件。 – Odyss3us 2010-03-22 09:02:42
好的..在這種情況下,我的解決方案並不是那麼好..讓我編輯它.. – 2010-03-22 09:05:15
在cron中,你也可以運行wget來保存php腳本的輸出。 – Krab 2010-03-22 09:13:06