当尝试使用php将多维数组导出到excel时,我只得到空的excel文件,我是新手使用phpExcel 我知道这样的问题已经被问到并得到了回答,但我厌倦了分析所有的答案, 我需要知道我的代码中的问题是什么,如何清除它以获得预期的输出。
我需要输出,如图像
<?php
ini_set('display_errors', 1);
require_once('/var/www/html/aws/arun/PHPExcel/Classes/PHPExcel.php');
$sheet = array();
$array1 = array("Body","ID","Group");
array_push($sheet,$array1);
$array2 = array("Mesaage 1" , "10", "11");
array_push($sheet,$array2);
echo '<pre>';
print_r($sheet);
echo '</pre>';
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('Excel Export');
foreach($sheet as $row => $val){
foreach($val as $column => $value){
$objPHPExcel->setActiveSheetIndex(0)->setCellValueByColumnAndRow($column, $row, $value);
}
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="test.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
?>
答案 0 :(得分:0)
使用下面的代码,如果适用于您,可以将文件导出到csv吗?
$sheet = array();
$array1 = array("Body","ID","Group");
array_push($sheet,$array1);
$array2 = array("Mesaage 1" , "10", "11");
array_push($sheet,$array2);
echo '<pre>';
print_r($sheet);
echo '</pre>';
//open file ready to write to
//'c+' opens the file or creates if it doesn't already exist
$fo = fopen('YOURFILEPATHHERE','c+');
//loop through array
foreach ($sheet as $lines) {
//push array values to line in the csv file
fputcsv($fo,$lines);
}
//close file
fclose($fo);
这会输出符合您要求的csv。
确保您有权写入您在YOURFILEPATHHERE指定的位置。
了解有关fputcsv和fopen的更多信息,请分别访问http://php.net/manual/en/function.fputcsv.php和http://php.net/manual/en/function.fopen.php。
答案 1 :(得分:0)
$row
, 1
需要从setCellValueByColumnAndRow()
开始,因为MS Excel工作表行从1开始(请注意,Excel永远不会有单元格A0
)< / p>
但您可能会发现使用Worksheet的fromArray()方法更容易
答案 2 :(得分:0)
尝试此代码,并根据您的要求进行一些更改
$header = array("Body","ID","Group");
$array2 = array("Mesaage 1" , "10", "11");
$list = array ($header);
$filename = "mmyexcel.xls";
$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet()->setTitle('Excel Export');
$list[] = $array2;
$sheet->fromArray($list);
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');