如何使用 PHP 从 mySQL 表创建 .XLS 文档?
我几乎尝试了所有方法,但没有成功。
基本上,我需要获取表格数据,并将其输入数据库,我已经完成了,然后我需要检索该表格数据并将其解析为 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 文件,我该怎么做呢?
我需要非常紧急地完成这项工作,因此非常感谢任何帮助。 谢谢大家。
最佳答案
如果您的数据库有某种前端(如 phpMyAdmin 或 SQLyog),您可以将表(或任何 SELECT 查询的结果)导出为 CSV 并在 Excel 中打开。
评论后编辑: 我创建了一个 XLS 一次。它有点不同,但我所做的是将它放在我的 PHP 的顶部(在生成任何输出之前):
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: attachment; filename=\"name.xls\"");
在脚本的其余部分,我只是回显了一个表格(表格、tr、td...等) 此脚本的执行将为用户提供下载。我认为 Content-disposition 属性有一些不同的选项(也许有一个可以让脚本保存文件)。
关于php - 使用 PHP 将 mySQL 转换为 XLS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2490866/