TIP게시판

제목 PHPExcel을 codeigniter에서 사용하기
글쓴이 변종원(웅파) 작성시각 2010/01/11 17:46:18
댓글 : 7 추천 : 1 스크랩 : 0 조회수 : 30416   RSS
원문 [http://virusandlinux.baskoroadi.web.id/index.php/2008/11/tutorial-write-and-read-excel-files-with-codeigniter/#more-49]

q&a게시판에 질문이 올라왔었는데 나중에 엑셀출력 쓸일이 있을 것 같아서 검색하다가 찾은 문서입니다.
hook을 이용하여 셋팅을 하네요.


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.

 다음글 개발참고용 codeigniter 라이브러리, 헬퍼 (3)
 이전글 [기타 제품]사용자 비번 보안 강화 (5)

댓글

최용운 / 2010/01/13 16:53:34 / 추천 0
 좋은 자료 감사합니다. 찾으려면 어려울텐데 이리 친절하게 .ㅎㅎ 나중에 우리 qna를 디렉토리화 해서 정리해둬도 .. 좋겠네요 .~~ 
미드필드 / 2010/01/22 06:54:33 / 추천 0
알아두면 좋은 팁이네욤..
가우리언 / 2010/03/26 11:41:35 / 추천 0
마침 필요해서 참고하여 엑셀파일 생성했습니다. 감사합니다. ^^
확실하게 잘 되네요.
PHPExcel 이라는 라이브러리도 꽤 괜찮은 녀석이구요...
다만, php.ini 에 time zone 이 설정되어 있어야, 에러 없이 정상 동작 합니다.
Nexist / 2013/03/20 10:53:30 / 추천 0
조금 더 쉽게 설명되어 있네요..
http://www.ncube.net/2034


phpexcel 사이트입니다
http://phpexcel.codeplex.com


변종원(웅파) / 2014/02/05 18:25:57 / 추천 1
hook이 아닌 third-party를 이용한 방식인데 더 간단합니다.

http://www.ahowto.net/php/easily-integrateload-phpexcel-into-codeigniter-framework
하늘치 / 2016/03/03 14:47:03 / 추천 0

// 변종원(웅파)

third_party 방식, 정말 간단하네요. ^^

테스트 해보니, centos7, php7, ci3.0.4 에서도 잘 작동합니다.

 

댓글을 남기는 이유는 다름 아닌, 주의해야 할 부분이 하나 있어서입니다.

코드 자체에 문제가 있다는 건 아니구요. ㅎㅎ

웅파님의 댓글을 따라 들어가보면 샘플 코드가 둘 있습니다.

그대로 복사해서 사용하면 공백 대신 보이지 않는 특수문자(→ ← 솔직히 이게 뭔지 모르겠습니다;) 같은 게 있어서 에러가 납니다.

그것만 주의하시면 되더라구요.

 

kaido / 2016/03/03 15:35:22 / 추천 0

이제 그 방식이 composer 방식으로 바뀌어 가고 있지요.

비슷한 건데 차이점은 자동설치와 수동설치의 차이?