我目前拥有的代码:
<?php
/** PHPExcel */
require_once '../Classes/PHPExcel.php';
/** PHPExcel_IOFactory */
require_once '../Classes/PHPExcel/IOFactory.php';
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set properties
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
->setLastModifiedBy("Maarten Balliauw")
->setTitle("Office 2007 XLSX Test Document")
->setSubject("Office 2007 XLSX Test Document")
->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
->setKeywords("office 2007 openxml php")
->setCategory("Test result file");
$result = 'select * from table1';
for($i=0;$i<count($result);$i++) {
$result1 = 'select * from table2 where table1_id = ' . $result[$i]['table1_id'];
for ($j=0;$j<count($result1);$j++) {
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $j, $result1[$j]['name']);
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Save Excel 2007 file
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
// Echo done
echo date('H:i:s') . " Done writing file.\r\n";
}
?>
上面的代码执行并将n个.xlsx文件保存在该文件夹中,但是我遇到的问题是在所有保存的excel文件中执行的for循环中最大的count(result1).
解决方法:
在深入之前,一件事很清楚
您没有执行$result的查询,也没有获取它,并且在$result1查询中您正在使用它,这是不可能的,
$result1存在相同的问题
您可以使用:
$result = mysql_query('select * from table1');
while($fetch_result=mysql_fetch_array($result))
{
$result2 = mysql("select * from table2 where table1_id = '".$fetch_result['table1_id']."'");
while($fetch_result2=mysql_fetch_array($result2)
{
--your code--
但是最好写JOIN而不是这两个查询