我正在使用Codeigniter和PHPexcelTo尝试将数组从db结果写入excel工作表。
我的数据由以下数据组成。
Array
(
[0] => stdClass Object
(
[ORDER] => 12334
[DATE] => 2015-10-05
[TEXT] => TEST
[TIME] => 06:03:03
[STATUS] => 1
)
[1] => stdClass Object
(
[ORDER] => 99999
[DATE] => 2015-10-05
[TEXT] => TEST2
[TIME] => 08:03:03
[STATUS] => 0
)
)
当我尝试使用phpexcel
将数据写入excel文件时,我得到类stdClass
的对象无法转换为字符串错误。
我希望excel文件的列名为Order
,Date
,Text
,Time
状态以及填充相应值的行。
这是我目前的代码
$this->load->library('excel');
$this->excel->setActiveSheetIndex(0);
$this->excel->getActiveSheet()->setTitle('test worksheet');
$this->excel->getActiveSheet()->fromArray($ordersArray, NULL, 'A1');
$filename='export.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
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($this->excel, 'Excel5');
//force user to download the Excel file without writing it to server's HD
$objWriter->save('php://output');
我认为它与数组中的对象存在问题,但我不确定如何使其工作。
答案 0 :(得分:4)
首先需要将对象转换为数组,使其成为二维数组:
array_walk(
$ordersArray,
function (&$row) {
$row = (array) $row;
}
);
$this->excel->getActiveSheet()->fromArray($ordersArray, NULL, 'A1');