3

I'm using Codeigniter and PHPexcelTo try and write an array from a db result to an excel worksheet.

I have array made of the following data.

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
    )

)

When I try to write the data to excel file using phpexcel I get the Object of class stdClass could not be converted to string error. I would like and excel file with the column names as Order,Date,Text,Time Status and the rows populated with the corresponding values.

Here is my current code

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

I believe its an issue with the objects within the array but i'm unsure how to make it work.

1 Answer 1

4

You'll need to cast the objects to arrays first, to make it a 2d-array:

array_walk(
    $ordersArray,
    function (&$row) {
        $row = (array) $row;
    }
);
$this->excel->getActiveSheet()->fromArray($ordersArray, NULL, 'A1');
Sign up to request clarification or add additional context in comments.

2 Comments

thanks Mark, how would i get the column names in there?
You mean as a header row? You'd need to extract those keys separately using something like $headers = array_keys($ordersArray[0]); first and write that array to A1, then your actual $ordersArray to A2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.