Long Live Open Source Software !!

I’ve got a problem when i use codeigniter to build a web application. There is no plugin or library that can create excel 2003 files perfectly. I used Spreadsheet::WriterExcel class to create an excel file. But i’ve got a problem when i merged some cells. Those cells is merged, but when i set a value, it appeared in the leftmost cell, not centered. I tried to find solution in google and the i found this site. It told me about how to use hook in codeigniter, so i can use another php library to write an excel file. In this case, i use PHPExcel, because it can create files like i want.

First, download PHPExcel library from its site. Don’t forget to fulfill its requirement. And then follow the steps below to use PHPExcel with CodeIgniter. I modify the tutorial from the site i told you above.

  1. Extract the PHPExcel library that you’ve just downloaded.
  2. Create a folder called my_classes in your system/application director
  3. Copy the folder [PHPExcel Directory]/Classes/ and its content in your system/application/my_classes/ directory.
  4. Enable hooks in your application/config/config.php file
    /*
    |--------------------------------------------------------------------------
    | Enable/Disable System Hooks
    |--------------------------------------------------------------------------
    |
    | If you would like to use the "hooks" feature you must enable it by
    | setting this variable to TRUE (boolean). See the user guide for details.
    |
    */
    $config['enable_hooks'] = TRUE;
  5. Add the following lines in application/config/hooks.php
    $hook['pre_controller'][] = array(
    'class' => 'MyClasses',
    'function' => 'index',
    'filename' => 'MyClasses.php',
    'filepath' => 'hooks'
    );
  6. In your system/application/hooks/ create a new file called MyClasses.php with the following inside.
    <?php
    if (!defined('BASEPATH')) exit('No direct script access allowed');

    class Myclasses
    {
    /**
    * includes the directory application\my_classes\Classes in your includes directory
    *
    */
    function index()
    {
    //includes the directory application\my_classes\Classes\
    ini_set('include_path', ini_get('include_path').':'.BASEPATH.'application/my_classes/Classes/');
    }
    }
    ?>

  7. If you use windows as your server, change the colon (:) to semicolon (;) in code above.
  8. Now you can use PHPExcel Library in CodeIgniter. Below is a simple controller example for you.
    <?php
    class Kiba extends Controller
    {
    function Kiba()
    {
    parent::Controller();
    }function testexcel()
    {
    include 'PHPExcel.php';
    /** PHPExcel_Writer_Excel2007 */
    include 'PHPExcel/Writer/Excel5.php';

    // Create new PHPExcel object
    echo date('H:i:s') . " Create new PHPExcel object\n";
    $objPHPExcel = new PHPExcel();

    // Set properties
    echo date('H:i:s') . " Set properties\n";
    $objPHPExcel->getProperties()->setCreator("BazZ");
    $objPHPExcel->getProperties()->setLastModifiedBy("BazZ");
    $objPHPExcel->getProperties()->setTitle("TestExcel");
    $objPHPExcel->getProperties()->setSubject("");

    // Set row height
    $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(50);
    $objPHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(25);

    // Set column width
    $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
    $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
    $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
    $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(40);
    $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30);
    $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(10);
    $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20);

    //Merge cells (warning: the row index is 0-based)
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(0,1,13,1);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(0,2,13,2);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(0,3,0,5);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(1,3,1,5);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(2,3,3,3);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(2,4,2,5);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(3,4,3,5);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(4,3,4,5);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(5,3,5,5);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(6,3,6,5);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(7,3,9,3);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(7,4,7,5);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(8,4,9,4);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(10,3,10,5);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(11,3,11,5);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(12,3,12,5);
    $objPHPExcel->getActiveSheet()->mergeCellsByColumnAndRow(13,3,13,5);

    //Modify cell's style
    $objPHPExcel->getActiveSheet()->getStyle('A1')->applyFromArray(
    array(
    'font' => array(
    'name'         => 'Times New Roman',
    'bold'         => true,
    'italic'    => false,
    'size'        => 20
    ),
    'alignment' => array(
    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    'vertical'   => PHPExcel_Style_Alignment::VERTICAL_CENTER,
    'wrap'       => true
    )
    )
    );

    $objPHPExcel->getActiveSheet()->getStyle('A2')->applyFromArray(
    array(
    'font' => array(
    'name'         => 'Times New Roman',
    'bold'         => true,
    'italic'    => false,
    'size'        => 14
    ),
    'alignment' => array(
    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
    'vertical'   => PHPExcel_Style_Alignment::VERTICAL_CENTER,
    'wrap'       => true
    )
    )
    );

    $objPHPExcel->getActiveSheet()->duplicateStyleArray(
    array(
    'font' => array(
    'name'         => 'Times New Roman',
    'bold'         => true,
    'italic'    => false,
    'size'        => 12
    ),
    'borders' => array(
    'top'        => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
    'bottom'    => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
    'left'        => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
    'right'        => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE)
    ),
    'alignment' => array(
    'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
    'vertical'   => PHPExcel_Style_Alignment::VERTICAL_CENTER,
    'wrap'       => true
    )
    ),
    'A3:N5'
    );

    // Add some data
    echo date('H:i:s') . " Add some data\n";
    $objPHPExcel->setActiveSheetIndex(0);

    $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Try PHPExcel with CodeIgniter');
    $objPHPExcel->getActiveSheet()->SetCellValue('A2',"Subtitle here");

    $objPHPExcel->getActiveSheet()->SetCellValue('A3',"No.");
    $objPHPExcel->getActiveSheet()->SetCellValue('B3',"Name");
    $objPHPExcel->getActiveSheet()->SetCellValue('C3',"Number");
    $objPHPExcel->getActiveSheet()->SetCellValue('C4',"Code");
    $objPHPExcel->getActiveSheet()->SetCellValue('D4',"Register");
    $objPHPExcel->getActiveSheet()->SetCellValue('E3',"Space (M2)");
    $objPHPExcel->getActiveSheet()->SetCellValue('F3',"Year");
    $objPHPExcel->getActiveSheet()->SetCellValue('G3',"Location");

    // Rename sheet
    echo date('H:i:s') . " Rename sheet\n";
    $objPHPExcel->getActiveSheet()->setTitle('Try PHPExcel with CodeIgniter');

    // Save Excel 2003 file
    echo date('H:i:s') . " Write to Excel2003 format\n";
    $objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
    $objWriter->save(str_replace('.php', '.xls', __FILE__));
    }
    }
    ?>

  9. Try code above and run it. You will get a .xls file in your controller directory.

If you have any question, feel free to ask me anytime. You can leave a comment or contact me via email. Thank you. Hope this tutorial can help you.

Reblog this post [with Zemanta]
Share this post here:
  • Facebook
  • Twitter
  • Google Bookmarks
  • Digg
  • del.icio.us

Maybe you like this post too : [Tutorial] Generate Model Class with CRUD in CodeIgniter and MySql

Recent Top Story :

Recent Search :

20 Responses to “[Tutorial] Write and Read Excel Files With CodeIgniter”

  1. zohaib Says:

    how we can add the name ranges in your code.

    Reply

    baskoro Reply:

    what do you mean? what name ranges?

    Reply

  2. johnny Says:

    kLFyCc Thanks for good post

    Reply

  3. Mangesh Says:

    baskoro,

    Thank you for posting this. I’m one step closer to reading Excel files in CI.

    I found a few errors. The quotes and double quotes featured inside the code are not regular for windows.

    They single-quotes should be ‘ instead of ‘ and ’.

    The double-quotes should be ” instead of ”.

    I was able to fix this fairly quickly with a find-replace all.

    In step 3 you state “Copy the folder [PHPExcel Directory]/Classes/ and its content in your system/application/my_classes/ directory.”

    To be more precise, this should state “Copy the folder [PHPExcel Directory]/Classes/ and its content in your system/application/my_classes/Classes/ directory.

    Reply

  4. Mangesh Says:

    Looks like it’s your code display. My single quotes are becoming the tick marks and my double quotes are becoming some strange ascii character.

    Reply

    baskoro Reply:

    thanks for your correction.
    but i can’t edit the single quotes. I don’t know why they appear like that.

    Reply

  5. Arivusudar Says:

    Hi..

    Thank you very much for your excellent coding.. it is very useful for codeigniter users..
    but i dont want to save file. i need download requiring format when file has been creating..

    Reply

    baskoro Reply:

    it’s simple, just replace :
    $objWriter->save(str_replace(‘.php’, ‘.xls’, __FILE__));
    with :
    $objWriter->save(‘php://output’);

    Reply

    Rilax Reply:

    Hi
    First thanks for your post it’s very useful.
    I use
    header(‘Content-Disposition:inline;filename=Fichier.xls ‘);
    $objWriter->save(’php://output’);
    To download the file but the file is corrupted.
    Did you have this problem?
    Can you help me?

    Reply

    baskoro Reply:

    maybe you have some error in your code, so the file created by phpexcel is corrupted

    Reply

  6. test Says:

    hello i integrate your code as yu said. but when i run my controller it gives me error like this

    Message: Writeexcel::include(PHPExcel.php) [function.Writeexcel-include]: failed to open stream: No such file or directory

    Filename: controllers/writeexcel.php

    Line Number: 11

    Message: Writeexcel::include() [function.include]: Failed opening ‘PHPExcel.php’ for inclusion (include_path=’.;C:\php5\pear:C:\Program Files\Apache Group\Apache2\htdocs\Mysimpleprofit/system/application/my_classes/Classes/’)

    Filename: controllers/writeexcel.php

    Line Number: 11

    Class ‘PHPExcel’ not found in C:\Program Files\Apache Group\Apache2\htdocs\Mysimpleprofit\system\application\controllers\writeexcel.php on line 17

    Reply

    baskoro Reply:

    @test : change the ‘:’ to semicolon (‘;’) in your hooks class

    Reply

  7. alan Says:

    Good post. It is very useful for codeigniter users.

    Reply

  8. CodeigniterでPHPExcel使用。 | 今、出来ることをやる。 Says:

    [...] codeigniterでhookを利用した使い方 [...]

  9. André Beaudry Says:

    It is generous of you, to share this information. Thank you very much.
    I have never used hook before.
    Always learning ….

    Reply

  10. @r13f Says:

    Why dont you drop the package in application/library folder, and just instantiated like usual CI library. It’s more convenient way than creating you own class folder i think. I’ve done this before and you dont have modify the include path in ini file.

    Reply

  11. Sasa Says:

    I am just getting the 404 not found message :sad: I named my controller kiba.php like the name of the class and I don’t know why it is not working.I know it is something simple but I just can’ get it to work.I also changed in my $config the default controller to kiba.Can anyone help?

    Reply

    baskoro Reply:

    I don’t think it’s caused by the filename maybe you have misstype character in your class name or filename

    Reply

  12. Thilga Says:

    it shows fatal error like below,

    Fatal error: Uncaught exception ‘Exception’ with message ‘Can’t open /opt/lampp/htdocs/CodeIgniter_2.0.2/application/controllers/kiba.xls. It may be in use or protected.’ in /opt/lampp/htdocs/CodeIgniter_2.0.2/application/my_classes/phpexcel/Classes/PHPExcel/Shared/OLE/PPS/Root.php:91 Stack trace: #0 /opt/lampp/htdocs/CodeIgniter_2.0.2/application/my_classes/phpexcel/Classes/PHPExcel/Writer/Excel5.php(185): PHPExcel_Shared_OLE_PPS_Root->save(‘/opt/lampp/htdo…’) #1 /opt/lampp/htdocs/CodeIgniter_2.0.2/application/controllers/kiba.php(146): PHPExcel_Writer_Excel5->save(‘/opt/lampp/htdo…’) #2 [internal function]: Kiba->testexcel() #3 /opt/lampp/htdocs/CodeIgniter_2.0.2/system/core/CodeIgniter.php(339): call_user_func_array(Array, Array) #4 /opt/lampp/htdocs/CodeIgniter_2.0.2/index.php(201): require_once(‘/opt/lampp/htdo…’) #5 {main} thrown in /opt/lampp/htdocs/CodeIgniter_2.0.2/application/my_classes/phpexcel/Classes/PHPExcel/Shared/OLE/PPS/Root.php on line 91

    it seems the could not create the xl file by apache.
    can anybody answer for this?

    Reply

    baskoro Reply:

    Please check your file ownership and permission

    Reply

Leave a Reply