使用PHPExcel获取错误

时间:2013-03-30 10:01:33

标签: php phpexcel

我试图在excel中导出mysql数据库表,即XLS格式,我已经尝试使用PHP代码获取excel格式的结果但是因为某些原因或某些缺少的术语我无法完成它,这是我的php代码:

<?php

// connection with the database
$dbcon = mysql_connect("127.0.0.1","root","mim");

if($dbcon)
{
    mysql_select_db("mydb", $dbcon);
}
else
{
    die('error connecting to the database');
}

// require the PHPExcel file
require 'Classes/PHPExcel.php';

$query = "
    SELECT name
    FROM usermaster
    WHERE date between '2013-01-01' AND '2013-03-01'
";
$result = mysql_query($query) or die(mysql_error());         

// Create a new PHPExcel object
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Name');

// Loop through the result set
$row = 1;
while ($row = mysql_fetch_row($result)) {
    $col = 0;
    foreach($row as $name) {
        $objPHPExcel->getActiveSheet()->setCellValue($col.$row,$name);
        $col++;
    }
    $row++;
}

// Save as an Excel BIFF (xls) file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="myFile.xls"');
header('Cache-Control: max-age=0');

$objWriter->save('php://output');
exit();

?>

获得一个空白的页面......任何形式的帮助都会受到赞赏和接受......

1 个答案:

答案 0 :(得分:0)

setCellValue()需要一个Excel单元格地址(例如A1,B2,C3,其中列ID是字母ID,后跟行号)作为第一个参数。您正在使用数字(从0开始)作为列ID。

不是将初始列ID设置为0,而是将其设置为“A”:

$row = 1;
while ($row = mysql_fetch_row($result)) {
    $col = 'A';
    foreach($row as $name) {
        $objPHPExcel->getActiveSheet()->setCellValue($col.$row,$name);
        $col++;
    }
    $row++;
}