Last active
August 31, 2022 04:57
-
-
Save rwaddin/fa019efb7493397785b4b3bac4d1e8fb to your computer and use it in GitHub Desktop.
embeed medium - create export excel with phpspreadsheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php if( ! defined('BASEPATH')) exit('No direct script access allowed'); | |
use PhpOffice\PhpSpreadsheet\Spreadsheet; | |
use PhpOffice\PhpSpreadsheet\Writer\Xlsx; | |
class Ratingexcel extends CI_controllers | |
{ | |
public function index() | |
{ | |
$spreadsheet = new Spreadsheet(); | |
$sheet = $spreadsheet->getActiveSheet(); | |
# membuat title data | |
$sheet->setCellValue('A1', 'No'); | |
$sheet->setCellValue('B1', 'Bintang'); | |
$sheet->setCellValue('C1', 'Waktu'); | |
$sheet->setCellValue('D1', 'Catatan'); | |
# membuat style jadi center antara kanan & kiri | |
$sheet->getStyle('A1:D1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); | |
$sheet->getStyle('A')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); | |
$sheet->getStyle('B')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER); | |
# membuat kolom waktu & catatan menjadi auto width / lebar mengikuti content | |
$sheet->getColumnDimension('C')->setAutoSize(true); | |
$sheet->getColumnDimension('D')->setAutoSize(true); | |
# contoh data yang akan di export | |
$records = array( | |
[ | |
"id"=> "1", | |
"rating"=> "4", | |
"message"=> "rating 4", | |
"created_at"=> "2022-07-15 08:41:19", | |
], | |
[ | |
"id"=> "2", | |
"rating"=> "5", | |
"message"=> "Bagus kak", | |
"created_at"=> "2022-08-09 16:12:36", | |
] | |
); | |
$initCell = 2; # untuk increment index cell | |
$no = 1; # untuk kolom nomor | |
foreach ($records as $record) { | |
$sheet->setCellValue("A{$initCell}", $no); | |
$sheet->setCellValue("B{$initCell}", $record["rating"]); | |
$sheet->setCellValue("C{$initCell}", $record["created_at"]); | |
$sheet->setCellValue("D{$initCell}", $record["message"]); | |
$initCell++; | |
$no++; | |
} | |
$writer = new Xlsx($spreadsheet); | |
# membuat nama file | |
$fileName = "Generate on ".date("Y-m-d H:i:s"); | |
# menyimpan di root project codeigniter | |
$writer->save("./{$fileName}.xlsx"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment