我正在尝试使用php excel将数组结果导出到excel。我想将此数据放入基于多个工作表的数组中。例如:在数组中,person_mast,person_ex应该为sheet1和sheet2,并且它们各自的数组应以数组键作为列标题,数组值作为数据在excel文件中的多行放置。
问题:
Not able to loop through array and put values in cells.
我的数组:
Array
(
[person_mast] => Array
(
[0] => Array
(
[details_id] => 10470
[head_id] => 1
[recdate] => 2011-02-23 00:00:00
)
[1] => Array
(
[details_id] => 38708
[head_id] => 1
[recdate] =>
)
)
[person_ex] => Array
(
[0] => Array
(
[details_id] => 9842
[head_id] => 19
[visit_dt] => 2014-08-07 00:00:00
[addinfo] => abc
)
[1] => Array
(
[details_id] => 10234
[head_id] => 20
[visit_dt] => 2007-11-20 00:00:00
[addinfo] => 3 3
)
)
)
我的代码:
$filename = "report_".date('Ymd_His').".xls";
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$sheet_count = '0';
foreach($patient_result as $tb_name => $tb_data){
$sheetname = $tb_name ;
if($sheet_count != '0'){
// Create a new worksheet, after the default sheet
$objPHPExcel->createSheet();
}
// Create a first sheet, representing sales data
$objPHPExcel->setActiveSheetIndex($sheet_count);
$column_count = 0;
foreach($tb_data as $key => $curr_data){
foreach($curr_data as $colname => $data){
//echo "<br>colname : ".$colname;
$objPHPExcel->getActiveSheet()->setCellValue($colname.$key, $data);
$column_count ++;
}
}
// Rename sheet
$objPHPExcel->getActiveSheet()->setTitle($sheetname);
$sheet_count++;
预期的Excel文件格式:
答案 0 :(得分:2)
工作表编号必须是整数,增量运算符只能与int val一起使用。必须定义标题部分(每张纸的列名),并且需要传递纸号以填充当前循环的数据。
只需输入此代码,它就可以100%工作
$objPHPExcel = new PHPExcel();
$filename = "report_".date('Ymd_His').".xls";
$sheet_title = array('person_mast','person_ex');
$sheet_count = 0;
foreach($patient_result as $tb_name => $tb_data){
$sheet = $objPHPExcel->createSheet($sheet_count);
$header_key = array_keys($tb_data[0]);
$header = array($header_key[0], $header_key[1], $header_key[2]);
$list = array ($header);
//$this->excel->setActiveSheetIndex($sheet_count);
$sheet->setTitle($sheet_title[$sheet_count]);
$tmp_row = array();
foreach($tb_data as $key => $curr_data){
//echo '<pre>'; print_r( $curr_data); exit;
$list[] = $curr_data;
}
$sheet->fromArray($list);
$sheet_count++; //break;
}
header('Content-Type: application/vnd.ms-excel');
//tell browser what's the file name
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0'); //no cache
//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
//if you want to save it as .XLSX Excel 2007 format
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//force user to download the Excel file without writing it to server's HD
//$objWriter->save('php://output');
$objWriter->save($filename);