In this post, I would like to show using of PhpSpreadsheet library within your CodeIgniter 3 project. PhpSpreadsheet is a pure PHP library for reading and writing spreadsheet files.
Here is my another post, you might be interested in – How to use PHPExcel with CodeIgniter?
Here are the steps to generate Excel in the CodeIgniter 3 application with PhpSpreadsheet:
Step 1: Download and install CodeIgniter.
Step 2: Run below composer command to download phpspreadsheet
library from your project folder. It will create a new folder called “vendor” and it will download phpoffice/phpspreadsheet
library into it.
1 |
$ composer require phpoffice/phpspreadsheet |
Here is my the directory structure after installing phpoffice/phpspreadsheet
Step 3: Open application/config/config.php
file and set you vendor directory path
1 |
$config['composer_autoload'] = 'vendor/autoload.php'; |
Step 4: Use phpspreadsheet library inside in your controller, here is the sample:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?php defined('BASEPATH') OR exit('No direct script access allowed'); use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; class Welcome extends CI_Controller { public function index() { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'Hello World !'); $writer = new Xlsx($spreadsheet); $filename = 'name-of-the-generated-file.xlsx'; $writer->save($filename); // will create and save the file in the root of the project } public function download() { $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); $sheet->setCellValue('A1', 'Hello World !'); $writer = new Xlsx($spreadsheet); $filename = 'name-of-the-generated-file'; header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="'. $filename .'.xlsx"'); header('Cache-Control: max-age=0'); $writer->save('php://output'); // download file } } |
For more information, here is the official documentation page of – phpspreadsheet documentation
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.