我想从数据库中检索数据行,以便在Symfony中导出Excel文件。我在循环遍历每一行时遇到问题,而我只得到结果的最后一个元素。我猜我在某个地方犯了一个错误,要么有正确的循环,要么它没有正确循环。或者我可能没有正确检索数据?我只习惯通过Doctrine检索数据并在twig模板中输出循环,所以这让我很困惑。非常感谢。
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('
.......query ')
->setParameter('no', $no);
$results = $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
$excel = $this->get('phpexcel')->createPHPExcelObject();
$excel->getProperties()->setCreator('iStyle')
->setTitle('Inventory Report');
$i = 2;
$excel->setActiveSheetIndex(0);
$excel->getActiveSheet()->setTitle('Inventory. '.$no)
->setCellValue('A1', 'Report')
->mergeCells('A1:G1')
->setCellValue('A'.$i, 'No.')
->setCellValue('B'.$i, 'Color')
->setCellValue('C'.$i, 'Weight')
->setCellValue('D'.$i, 'SKU')
->setCellValue('E'.$i, 'Dimensions')
->setCellValue('F'.$i, 'Qty Available');
for($d = 0; $d < count($results); $d++) {
$i = 3;
$excel->getActiveSheet()
->setCellValue('A'.$i, $results[$d]['no'])
->setCellValue('B'.$i, $results[$d]['color'])
->setCellValue('C'.$i, $results[$d]['weight'])
->setCellValue('D'.$i, $results[$d]['sku'])
->setCellValue('E'.$i, $results[$d]['dimensions'])
->setCellValue('F'.$i, $results[$d]['qty']);
$i++;
}
$writer = $this->get('phpexcel')->createWriter($excel, 'Excel5');
$response = $this->get('phpexcel')->createStreamedResponse($writer);
$response->headers->set('Content-Type', 'text/vnd.ms-excel; charset=utf-8');
$response->headers->set('Content-Disposition', 'attachment;filename=invreport-'.$no.'.xls');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
return $response;
答案 0 :(得分:2)
在for
循环中,您将$i
明确设置为3
,然后将其$i++
递增。因此,您永远不会添加新行,只需一遍又一遍地更新最后一行A3
,B3
,etc
,并留下最后一行进行更新。
将$i = 3;
移出循环并将其放在for(..)
来电之前。
示例强>
$i = 3;
for($d = 0; $d < count($results); $d++) {
$excel->getActiveSheet()
->setCellValue('A'.$i, $results[$d]['no'])
->setCellValue('B'.$i, $results[$d]['color'])
->setCellValue('C'.$i, $results[$d]['weight'])
->setCellValue('D'.$i, $results[$d]['sku'])
->setCellValue('E'.$i, $results[$d]['dimensions'])
->setCellValue('F'.$i, $results[$d]['qty']);
$i++;
}