SQL查询结果写入Excel

时间:2014-01-15 07:54:35

标签: php sql excel

好的,所以除了安装PHPexcel

之外,我不知道如何做到这一点

但是说我在数组中有查询结果

$mysqli = new mysqli('server', 'user1', 'pass', 'users');
if ($mysqli->connect_error)
     die(connect error ('.$mysqli->connect_error.') '.$mysqli->connect_error);

$date = date("Y-m-d");
$query = "SELECT * from usr WHERE date = '$date'";
while($row = $query->fetch_array()) {
     //EXCEL STUFF???
}

然后我将如何将其写入Excel电子表格? 任何帮助表示赞赏

2 个答案:

答案 0 :(得分:2)

1st:你有语法错误:

$mysqli = new mysqli('server', 'user1', 'pass', 'users');
if ($mysqli->connect_error)
     die('Connect Error: ' . $mysqli->connect_error);

$date = date("Y-m-d");
$query = "SELECT * from usr WHERE date = '$date'";

while($row = $query->fetch_array()) {
     //EXCEL STUFF???
}

第二,您可以将其作为普通表输出,并将其添加到标题中:

header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=abc.xls");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

此脚本将自动允许您下载包含您内容的名为abc.xls的文件。

答案 1 :(得分:0)

您可以使用PHPExcel写入或读取Excel工作表。

链接:https://github.com/PHPOffice/PHPExcel

以下是读取/写入Excel的示例代码

http://phpexcel.codeplex.com/wikipage?title=Examples

//来自网站的最低样本代码:

include 'PHPExcel/Writer/Excel2007.php';

// Create new PHPExcel object

$objPHPExcel = new PHPExcel();
// Add some data

$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Hello');

// Save Excel 2007 file

$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));