PHPExcel setCellValueByColumnAndRow不将数据写入电子表格

时间:2012-07-13 10:23:41

标签: php phpexcel

我正在使用PHPExcel将数据从mysql数据库输出到excel工作簿。我的工作簿有3张,大部分工作正常。我输出到第三张表的最后一部分有问题。我要做的是输出一个带有行标题和列标题的表,其值取自mysql表,然后每行/列组合的数字也取自mysql表,基于该行/列标题是什么。行和列标题将按原样写入文件,但内部表格不是。当我将输出回显到屏幕时,所有数据都出现并且行/列迭代正在递增,因为它们应该只是setCellValueByColumnAndRow似乎没有设置工作表中的值。我遇到问题的代码部分如下。任何人都可以看到我的代码中的问题在哪里?

$objPHPExcel->setActiveSheetIndex(2);

while($srow = mysql_fetch_assoc($query_company))
{
$newarray[] = $srow['entity'];
}
$row4 = 2;
$col4 = 1;
while($trow = mysql_fetch_row($query_ctry))
{
$country = $trow[0];

while($comp = each($newarray))
{
$company = $comp[1];
$total = mysql_query("SELECT noparts FROM totalslist WHERE country = '$country' AND entity = '$company'") or die (mysql_error());
if ($numrows = mysql_num_rows($total) == 0)
{
$totalres = 0;
}
else
{
$result3 = mysql_fetch_row($total);
$totalres = $result3[0];
}

$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col4, $row4, $totalres); 
$col4++;

}
reset($newarray);
$row4++;
$col4 = 1;
}

1 个答案:

答案 0 :(得分:2)

**解决方案! 实际上我通过稍微改变代码解决了这个问题。我首先编写行和列标题,然后添加内部表值。我更改了它,因此我在行和列中增加了标题和数据,如下面的代码所示。可能会帮助别人。

$objPHPExcel->createSheet(2);
$objPHPExcel->setActiveSheetIndex(2);
$objPHPExcel->getActiveSheet()->setTitle('PivotTable');
$query_ctry = mysql_query("SELECT DISTINCT country FROM totalslist ORDER BY country");
$numctry = mysql_num_rows($query_ctry);
$query_company = mysql_query("SELECT DISTINCT entity FROM totalslist ORDER BY entity");
$numcomp = mysql_num_rows($query_company);

while($srow = mysql_fetch_assoc($query_company))
{
    $newarray[] = $srow['entity'];
}
$row3 = 2;
$col3 = 1;
while($trow = mysql_fetch_row($query_ctry))
{
    $country = $trow[0];

    while($comp = each($newarray))
    {
        $company = $comp[1];
        $total = mysql_query("SELECT noparts FROM totalslist WHERE country = '$country' AND entity = '$company'");
    if ($numrows = mysql_num_rows($total) == 0)
    {
        $totalres = 0;
    }
    else
    {
        $result3 = mysql_fetch_row($total);
        $totalres = $result3[0];
    }
    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $row3, $country);
    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col3, 1, $company);
    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col3, $row3, $totalres); 
    $col3++;

    }
        reset($newarray);
        $row3++;
        $col3 = 1;
}
        // Save Excel file
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit();