CodeIgniter 4 Export Data to Excel or CSV Using PHPexcel & Download

In this tutorial, we will learn how to export data from CodeIgniter 4 to Excel or CSV using PHPexcel and download it.

PHPExcel is a library written in pure PHP and providing a set of classes that allow you to write to and read from different spreadsheet file formats, like Excel (BIFF) .xls, Excel 2007 (OfficeOpenXML) .xlsx, CSV, Libre/OpenOffice Calc .ods, Gnumeric, PDF, HTML, etc.

We will use the PHPExcel library to export data from CodeIgniter 4 to Excel or CSV.

Step 1: Install PHPExcel Library

First, we need to install the PHPExcel library in our CodeIgniter 4 application. We can install it using Composer.

Run the following command in the terminal to install the PHPExcel library:

composer require phpoffice/phpexcel

Step 2: Create a Controller

Now, we will create a controller named ExportController.php in the app/Controllers directory.

‘John’, ‘age’ => ’20’], [‘name’ => ‘Smith’, ‘age’ => ’30’], [‘name’ => ‘Alex’, ‘age’ => ’25’] ]; // Create new PHPExcel object $objPHPExcel = new PHPExcel(); // Set document properties $objPHPExcel->getProperties()->setCreator(“CodeIgniter”) ->setLastModifiedBy(“CodeIgniter”) ->setTitle(“Export Data to Excel”) ->setSubject(“Export Data to Excel”) ->setDescription(“Export Data to Excel using PHPExcel in CodeIgniter 4.”) ->setKeywords(“excel export php”) ->setCategory(“export”); // Add some data $objPHPExcel->setActiveSheetIndex(0) ->setCellValue(‘A1’, ‘Name’) ->setCellValue(‘B1’, ‘Age’); // Miscellaneous glyphs, UTF-8 $i = 2; foreach ($data as $row) { $objPHPExcel->setActiveSheetIndex(0) ->setCellValue(‘A’ . $i, $row[‘name’]) ->setCellValue(‘B’ . $i, $row[‘age’]); $i++; } // Rename worksheet $objPHPExcel->getActiveSheet()->setTitle(‘Export Data’); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $objPHPExcel->setActiveSheetIndex(0); // Redirect output to a client’s web browser (Excel2007) header(‘Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’); header(‘Content-Disposition: attachment;filename=”export_data.xlsx”‘); header(‘Cache-Control: max-age=0’); // If you’re serving to IE 9, then the following may be needed header(‘Cache-Control: max-age=1’); // If you’re serving to IE over SSL, then the following may be needed header(‘Expires: Mon, 26 Jul 1997 05:00:00 GMT’); // Date in the past header(‘Last-Modified: ‘ . gmdate(‘D, d M Y H:i:s’) . ‘ GMT’); // always modified header(‘Cache-Control: cache, must-revalidate’); // HTTP/1.1 header(‘Pragma: public’); // HTTP/1.0 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, ‘Excel2007’); $objWriter->save(‘php://output’); } }

Step 3: Run the Application

Now, we can run the application using the following URL in the browser:

http://localhost/export

It will download the Excel file with the exported data.
[ad_1]

Export data to excel or csv in Codeigniter using PHPExcel; In this tutorial, you will learn how to create & export data in excel format using PHP excel with CodeIgniter 4.

Sometimes, you need to export data from database in excel csv format file with codeigniter 4 app. So, this tutorial will help you step by step on how to export dynamic data in Excel csv format with CodeIgniter 4 app using library PhpSpreadsheet to create and save dynamic Excel file to export and save data.

Let’s follow the following steps to create & export data into excel csv format or create and save dynamic data in excel file using PHP excel library in CodeIgniter 4 apps:

  • Step 1: Setup Codeigniter 4 Project
  • Step 2: Basic Configurations
  • Step 3: Create Table in Database
  • Step 4: Setup Database Credentials
  • Step 5: Download PhpSpreadsheet Libraray
  • Step 6: Create Controller
  • Step 7: Create Route
  • Step 8: Start Development Server

Step 1: Setup Codeigniter 4 Project

In this step, you will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”

Step 2: Basic Configurations

Next, you will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3: Create Table in Database

In this step, you need to create table in database and as well as insert some data for export data in codeiginter 4. So visit your phpmyadmin panel and execute the following sql query in it:

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `skills` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `designation` varchar(255) NOT NULL,
  `age` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `name`, `skills`, `address`, `designation`, `age`) VALUES
(1, 'Smith s', 'Java', 'Sydney', 'Software Engineer', 34),
(2, 'David', 'PHP', 'London', 'Web Developer', 28),
(3, 'Rhodes', 'jQuery', 'New Jersy', 'Web Developer', 30),
(4, 'Sara', 'JavaScript', 'Delhi', 'Web Developer', 25),
(5, 'Shyrlin', 'NodeJS', 'Tokiyo', 'Programmer', 35),
(6, 'Steve', 'Angular', 'London', 'Web Developer', 28),
(7, 'Cook', 'MySQL', 'Paris', 'Web Developer', 26),
(8, 'Root', 'HTML', 'Paris', 'Web Developer', 28),
(9, 'William', 'jQuery', 'Sydney', 'Web Developer', 23),
(10, 'Nathan', 'PHP', 'London', 'Web Developer', 28),
(11, 'Shri', 'PHP', 'Delhi', 'Web Developer', 38),
(12, 'Jay', 'PHP', 'Delhi, India', 'Web Developer', 30);

Step 4: Setup Database Credentials

In this step, you need to connect our project to the database. you need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, you need to set up database credentials in this file like below.

	public $default = [
		'DSN'      => '',
		'hostname' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'demo',
		'DBDriver' => 'MySQLi',
		'DBPrefix' => '',
		'pConnect' => false,
		'DBDebug'  => (ENVIRONMENT !== 'production'),
		'cacheOn'  => false,
		'cacheDir' => '',
		'charset'  => 'utf8',
		'DBCollat' => 'utf8_general_ci',
		'swapPre'  => '',
		'encrypt'  => false,
		'compress' => false,
		'strictOn' => false,
		'failover' => [],
		'port'     => 3306,
	];

Step 5: Download PhpSpreadsheet Libraray

In this step, you need to download PHP libraray PhpSpreadsheet to create and save dynamic Excel file. So, open your terminal and execute the following command on it:

composer require phpoffice/phpspreadsheet

Then open application/config/config.php file and set you vendor directory path.

$config['composer_autoload'] = 'vendor/autoload.php';

Step 6: Create Controller

In this step, Visit app/Controllers and create a controller name ExcelExport.php. In this controller, you need to add the following methods into it:

<?php namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;
use App\Models\UserModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ExcelExport extends Controller
{


  public function index() {

      $db      = \Config\Database::connect();
      $builder = $db->table('users');   

      $query = $builder->query("SELECT * FROM users");

      $users = $query->getResult();
      
      $fileName = 'users.xlsx';  
      $spreadsheet = new Spreadsheet();

      $sheet = $spreadsheet->getActiveSheet();
      $sheet->setCellValue('A1', 'Id');
      $sheet->setCellValue('B1', 'Name');
      $sheet->setCellValue('C1', 'Skills');
      $sheet->setCellValue('D1', 'Address');
      $sheet->setCellValue('E1', 'Age');
      $sheet->setCellValue('F1', 'Designation');       
      $rows = 2;

      foreach ($users as $val){
          $sheet->setCellValue('A' . $rows, $val['id']);
          $sheet->setCellValue('B' . $rows, $val['name']);
          $sheet->setCellValue('C' . $rows, $val['skills']);
          $sheet->setCellValue('D' . $rows, $val['address']);
          $sheet->setCellValue('E' . $rows, $val['age']);
          $sheet->setCellValue('F' . $rows, $val['designation']);
          $rows++;
      } 
      $writer = new Xlsx($spreadsheet);
      $writer->save("upload/".$fileName);
      header("Content-Type: application/vnd.ms-excel");
      redirect(base_url()."/upload/".$fileName); 
  }

}

Step 7: Create Route

In this step, you need to create a route that renders the table into the view, place the following code in app/Config/Routes.php file.

$routes->get('/', 'ExcelExport::index');

Step 8: Start Development Server

In this step, open your terminal and execute the following command to start development sever:

php spark serve

Then, Go to the browser and hit below the URL:

http://localhost:8080

Conclusion

Export data to excel in CodeIgniter using PHP excel. In this tutorial, you have learned how to export data to excel in codeigniter 4 app using phpexcel.

Recommended CodeIgniter 4 Tutorial

If you have any questions or thoughts to share, use the comment form below to reach us.

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00