PHP MySQL到PHPExcel未显示数据

PHP MySQL到PHPExcel未显示数据,php,phpexcel,Php,Phpexcel,/*它可以工作,但当我打开excel工作表时,它不工作,因此我删除了else语句中的echo和整个else,因此它可以工作,但没有将数据打印到工作表中*/ include_once 'PHPExcel.php'; $sheet = new PHPExcel(); $servername = $username = $password = $dbname = $conn = new mysqli($servername, $username, $password, $dbname); if

/*它可以工作,但当我打开excel工作表时,它不工作,因此我删除了else语句中的echo和整个else,因此它可以工作,但没有将数据打印到工作表中*/

include_once 'PHPExcel.php';
$sheet = new PHPExcel();


$servername =
$username = 
$password =
$dbname = 
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT firstname, lastname, phonenumber FROM people where answer='true' LIMIT ".$start.",10 ";

$result = $conn->query($sql);


if ($result->num_rows > 0) {
        // output data of each row
        $activeSheet=$sheet->getActiveSheet();
        while($row = $result->fetch_assoc()) {

        $activeSheet->setCellValue('A1',' $row["firstname"]');
        $activeSheet->setCellValue('B1','$row["lastname"]');
        $activeSheet->setCellValue('C1','$row["phonenumber"]');
        }
    } else {
        echo "0 results";
}
$conn->close();         
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename="report.xlsx"');
header('Cache-Control: max-age=0');

$objWriter=PHPExcel_IOFactory::createWriter($sheet,'Excel2007');
$objWriter->save('php://output'); 
exit;
两件事:

在此代码中

$activeSheet->setCellValue('A1',' $row["firstname"]');
语句,您不应该在
$row
部分周围使用任何引号,请删除它们:

$activeSheet->setCellValue('A1', $row["firstname"]);
另外,您的
else
子句在头之前输出数据,导致发送不正确的数据。卸下
else
。如果没有数据,您只会得到一个空的Excel文件

最后,将所有数据反复放在同一单元格中。使用变量增加到行数:

$i = 1;
while ($row = ...) {
    ...
    $activeSheet->setCellValue('A'+$i, $row["firstname"]);
    ...
    $i++;
}

它到底有什么表现吗?您得到的错误是什么,您希望得到什么?当我打开它时,它显示excel错误类型错误。。。但是,当我删除else语句时,它不会将数据打印到表单上。不要将您的密码放在公共论坛中!我删除了它,这是一个错误。您真的想将数据库中的每一行写入screadsheet中的第1行吗?但是如果您得到的是一张空白表,那么请确保您的SQL查询实际返回了数据哦,它工作了!!但是我怎样才能打印所有的值。。。现在它只是将数据显示到excel中的第一行,仅显示第一项!您可以在这些相同的单元格中反复写入所有数据。使用变量增加行数。我会更新我的答案。它起作用了,但为什么当我检索数字时,当它转换为excel时,它会复制为十六进制?