Question

i am working on a Cakephp 2.x .. i am using this solution for exporting data into excel sheet .. the problem is i dont know how can i add the column names or headings and then put data under the columns ..

for example here is what i am doing at the moment

$this->CSV->addRow(array_keys($line));
 foreach ($Contacts as $contact)
 {
      $line = $contact['Contact'];

       $this->CSV->addRow($line);
 }

$filename='orders';
 echo  $this->CSV->render($filename); 

what i want to make my excel sheet is like this as when i do in my view pages ..

      <table>

<tr>

    <th>Title</th>
    <th>Body</th>
    <th>Actions</th>
</tr>
<?php foreach($contacts as $contacts){?>
    <tr>

        <td> hello</td>
        <td> hello</td>
        <td> hello</td>
     </tr>
 }
    ?>
Was it helpful?

Solution

My recommendation is to use PHPExcel.

Here is what I have done:

I downloaded the PHPExcel files into Vendor folder.

My structure is now:

app 
  |---Vendor
        |----- PHPExcel
                   |----PHPExcel
                   |----PHPExcel.php

I needed to make my own forked changes to the PHPExcel for my own reasons. Hence I downloaded a copy instead of using the latest from repository with a package management solution like git submodules or composer. Feel free to use those.

Then I wrote my own Lib code in my cakephp app.

app 
  |---Lib
        |----- Print
                   |----Excel
                          |----SomeExcel.php
                          |----AnotherExcel.php

I wrote two classes SomeExcel and AnotherExcel because I needed to generate two different excel files.

Inside SomeExcel I wrote something like this:

require_once(APP . DS . 'Vendor' . DS . 'PHPExcel' . DS . 'PHPExcel.php');

class SomeExcel {
    private $yourOwnPrivateProperty;
    private $objPHPExcel;

    public function __construct($data) {
        $this->objPHPExcel    = new PHPExcel();
        $this->objPHPExcel->writeDebugLog = true;

        $this->_createFilename();

    }

    public function create() {
        // you have to study PHPExcel yourself and write this
        $this->_setFileProperties();
        // you have to study PHPExcel and write whatever you want
        $this->_createSheets();
        $result = $this->_save();

        if ($result) {
            return $this->_getAttachmentFormat();
        } else {
            return $result;
        }
    }

    protected function _save() {
        $objWriter = PHPExcel_IOFactory::createWriter($this->objPHPExcel, 'Excel2007');
        /* I will create the folder inside the webroot outputfiles folder 
         * in case it does not exist.
         * I am not going to provide it here as it is not relevant to the question.
         * You need to write your own.
         */
        $this->_createFolder(); 
        try {
            $objWriter->save($this->outputPath . $this->filename);
        } catch (Exception $e) {
            return false;
        }
        return true;
    }

    protected function _getAttachmentFormat() {
        return array(
            $this->filename => array(
                'file' => $this->outputPath . $this->filename,
                'mimetype' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'contentId' => 'excelfile-for-something'
            )
        );
    }

The AnotherExcel class is similar.

Usually it is a controller action that triggers the generation of an Excel file. However, to obey the FatModel-ThinController principle, I have a Model method to do that.

So I have a controller action that is like this:

/**
 * print_to_excel method (testing only)
 *
 * @return void
 */
public function print_to_excel($id = null) {
    set_time_limit(120);
    $result = $this->SomeModel->printExcel($id);

    if (is_array($result)){
        $filename = key($result);
        $this->redirect('/outputfiles/Excel/' . $id . '/' . $filename);
    }
}

Inside my SomeModel, I have the following:

/**
 *
 * print excel file for said Quotation
 *
 * @param $id Quotation id
 * @throws NotExistException
 * @return boolean Return true if successful
 */
public function printExcel($id = null) {
    if (!$this->exists($id)) {
        throw new NotFoundException(__('Invalid whatever'));
    }


    $data = $this->find('first', array(
        'conditions' => array('SomeModel.id' => $id),
    ));

    // do whatever you need to get the data you want printed in the Excel

    App::uses('SomeExcel', 'Lib/Print/Excel');

    $someExcel = new SomeExcel($data);

    return $someExcel->create();
}

This is my way of using Excel and CakePHP

It is one way, but not the only way.

I am also proud to tell you that this is the exact code I use for an enterprise app I wrote for a major telco company to do their own internal digital paperwork.

It is used by at least 10 people in that company.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top