Thursday, 23 August 2018

Codeigniter: Write / Export to Excel with Spout Library


Previously we discussed how to read a large Excel file with Spout. Now it's time to make how to write or Export from PHP to Excel.

Read: Codeigniter: Read Excel (Large) Files with Spout

Here are the steps

1. Prepare your Codeigniter project folder

2. Download the Library Spout here

3. Copy Paste the Spout Library folder to application / third_party

The Spout structure folder will be like this



If so, create an Export.php Controller

<? php defined ('BASEPATH') OR exit ('No direct script access allowed');
/ **
 * Export to Excel with CI and Spout
 *
 * @author budy k
 *
 * /

// load Spout Library
require_once APPPATH. '/ third_party / spout / src / Spout / Autoloader / autoload.php';

// lets Use the Spout Namespaces
use Box \ Spout \ Writer \ WriterFactory;
use Box \ Spout \ Common \ Type;

Export class extends Publicapi_Controller
{
    public function index ()
    {
        $ writer = WriterFactory :: create (Type :: XLSX);
        // $ writer = WriterFactory :: create (Type :: CSV); // for CSV files
        // $ writer = WriterFactory :: create (Type :: ODS); // for ODS files

        // stream to browser
        $ writer-> openToBrowser ("testing.xlsx");

        $ header = [
            'No SP',
            'SP Date',
            'Payment'
        ];
        $ writer-> addRow ($ header); // add a row at a time

        $ rows =
            ['SP-903923', '2017-11-12', '35'],
            ['SP-6546', '2017-10-29', '7567'],
            ['SP-546546', '2017-08-29', '3453'],
            ['SP-675677', '2017-02-29', '4654'],
            ['SP-324344', '2017-12-29', '9789']
        ];

        $ writer-> addRows ($ rows); // add multiple rows at a time

        $ writer-> close ();

    }
}
For those who use data from the database, please adjust and fill the variable $ rows with data from the database

Run in the browser

http: //localhost/my-project/index.php/export
or

http: // localhost / my-project / export
It's good to use Spout, we just define everything (Headers and Rows) in Array only and Sport will automatically create Columns and rows. Spout is also very good for large data / for example thousands to tens of thousands of rows.

Good luck. Don't forget Share well.

Share this


0 Comments