4

我正在使用 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;
}
4

1 回答 1

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();
于 2012-07-14T17:51:31.687 回答