Codeigniter Export To Word – Beberapa waktu yang lalu dapat kerjaan bikin laporan dengan format word. Dulu sih pernah bikin pake template word, tapi karena lupa akhirnya nyari-nyari class word yang cocok , akhirnya nemu juga class wordnya. Namanya adalah phpWord. Ada 2 class yang saya temukan yaitu buatan PHPOffice dan Codeplex.
Dalam tulisan saya ini, saya menggunakan class word buatan Codeplex karena saya anggap lebih mudah jika dibandingkan dengan PHPOffice. Silahkan download terlebih dahulu class wordnya disini. Kemudian copy kan folder phpWord nya ke dalam folder third_party. Kemudian buatlah sebuah library dengan nama word.php yang isinya adalah:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH."/third_party/PHPWord/PHPWord.php";
class Word extends PhpWord
{
public function __construct()
{
parent::__construct();
}
}
Kemudian untuk generate exportnya perintah yang digunakan adalah:
$this->load->library('word');
$section = $this->word->createSection();
$section->addText('Hello world!');
$section->addText('Hello world! I am formatted.', array('name'=>'Tahoma', 'size'=>16, 'bold'=>true));
$section->addText('Hello world! I am formatted by a user defined style', 'myOwnStyle');
$objWriter = PHPWord_IOFactory::createWriter($this->word, 'Word2007');
$objWriter->save('helloWorld.docx');
Jika menginginkan untuk agar ketika setelah digenerate akan langsung membuka file yang digenerate tinggal menambahkan perintah berikut ini:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);
unlink($filename);
Sehingga hasilnya keseluruhan perintahnya adalah:
$this->load->library('word');
$section = $this->word->createSection();
$section->addText('Hello world!');
$section->addText('Hello world! I am formatted.', array('name'=>'Tahoma', 'size'=>16, 'bold'=>true));
$section->addText('Hello world! I am formatted by a user defined style', 'myOwnStyle');
$filename = 'helloWorld.docx';
$objWriter = PHPWord_IOFactory::createWriter($this->word, 'Word2007');
$objWriter->save($filename);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
flush();
readfile($filename);
unlink($filename);
Untuk file selengkapnya silahkan download disini. Semoga bermanfaat
