4

PHPExcelを使用してmysqlデータベースからExcelワークブックにデータを出力しています。私のワークブックには3枚のシートがあり、ほとんどが正常に機能しています。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

**Solution! Actually I solved this problem by changing the code slightly. I was writing the row and column headers first and then adding the inner table values after. I changed it so that I added the headers and data as I incremented through the rows and columns as shown in code below. Might help someone else.

$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 に答える