2013-03-30 70 views
1

我想在Excel中導出mysql數據庫表格,即在XLS格式中,我嘗試了PHP代碼獲取excel格式的結果,但由於某種原因或某些缺失的術語我無法完成,這是我的PHP代碼:獲取PHPExcel錯誤

<?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(); 

?> 

獲得一個空白頁......任何形式的幫助,將不勝感激,也可以接受......

+0

請學會正確的縮進你對別人造成你的代碼之前。 – Hubro

+1

請參閱http://phpexcel.codeplex.com/discussions/250120 – worenga

+0

也許你的環境配置有問題;看到這個其他堆棧http://stackoverflow.com/questions/6201176/phpexcel-objwriter-save-fails –

回答

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++; 
} 
+0

嘗試ths,但仍然沒有得到結果......... –

+0

好吧,從一些基本的調試開始......保存到文件而不是php://輸出,並在代碼中放置一些echo語句以查看什麼值寫入哪個單元 –

+0

嗨馬克我提到你的答案和評論,同時通過參考不同的問題對你的知識有所瞭解,請幫助我...... –