1

我正在尝试以 excel 即 XLS 格式导出 mysql 数据库表,我尝试使用 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();

?>

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

4

1 回答 1

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++;
}
于 2013-03-30T10:50:20.000 回答