2015-12-14 55 views
0

/*它可以工作,但是当我打开Excel工作表时,它不工作,所以我删除了else语句中的echo以及其他所有工作,所以它工作但没有将数据打印到工作表*/PHP MySQL到PHPExcel没有显示数据

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; 
+1

它显示什么吗?你得到的错误是什么,你期望什么? –

+0

它显示excel错误,当我打开它的类型错误...但是当我删除else语句它的工作原理而不打印数据到工作表 –

+0

不要把你的密码在公共论坛! –

回答

0

两件事情:

在这段代码

$activeSheet->setCellValue('A1',' $row["firstname"]'); 

语句,你不应该使用周围的$row部分的任何引号,删除它们:

$activeSheet->setCellValue('A1', $row["firstname"]); 

另外,您的else子句在标头之前输出数据,从而导致发送不正确的数据。删除else。如果没有数据,则最终只有一个空的Excel文件。

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

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

哦,它的工作!但是我怎样才能打印所有这些值...现在它只显示数据到excel中的第一行只有第一项! –

+0

您可以一次又一次地写入这些相同单元格中的所有数据。使用一个变量来增加行。我会更新我的答案。 –

+0

它的工作,但为什么当我检索数字,当它转换为Excel复制为十六进制? –