将mysql数据库导出为ex​​cel

时间:2012-03-15 16:05:57

标签: php mysql database phpexcel

我一直在尝试使用下面的脚本将mysql数据库的内容导出到excel无济于事。我一定是做错了一些错误:

$getExcel = "SELECT name, age, course, city FROM person";
$res = mysql_query($getExcel);


/** Error reporting */
error_reporting(E_ALL);

date_default_timezone_set('Europe/London');

/** PHPExcel */
require_once 'Classes/PHPExcel.php';


// Create new PHPExcel object
echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();

if(!$res){
    die("Error");
}
$col = 0; 
$row = 0; 
while($row = mysql_fetch_assoc($res)) { 
    foreach($row as $key=>$value) { 
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value); 
        $col++; 
    } 
    $row++; 
} 

// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

// Save Excel 2007 file
echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('record.xlsx');

我做错了什么?

1 个答案:

答案 0 :(得分:4)

您的问题很可能是在两个不同的上下文中使用变量$row ...试试这个:

$row = 1; 
while($mrow = mysql_fetch_assoc($res)) { 
    $col = 0; 
    foreach($mrow as $key=>$value) { 
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value); 
        $col++; 
    } 
    $row++; 
}