将数组导出到PHPExcel产生数组到字符串转换错误

我正在使用Codeigniter和PHPexcel尝试将数据库结果中的数组写入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 Status,并用相应的值填充行.

这是我当前的代码

$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');

我相信这与数组中的对象有关,但是我不确定如何使其工作.

解决方法:

您需要首先将对象转换为数组,以使其成为2d数组:

array_walk(
    $ordersArray,
    function (&$row) {
        $row = (array) $row;
    }
);
$this->excel->getActiveSheet()->fromArray($ordersArray, NULL, 'A1');
上一篇:PHP-将数字转换为Excel的字符串


下一篇:phpexcel库在localhost上运行良好,但在服务器中生成空白的excel文件