J3.x

J3.x:Developing a component frontend update function/Excel xlsx export

From Joomla! Documentation

Joomla! 
3.x
Tutorial
Developing a component frontend update function


22 Excel export using PHPExcel

22.1 Description

As an example of a more elaborate export feature the HelloWorld version of the previous step has been enhanced with an option to download the data from the database as an xlsx Excel file. For the conversion the PHPExcel packages is used. The current PHPExcel version can be downloaded here .

22.2 Install PHPExcel

The installation of PHPExcel is quite straightforward as explained in the PHPExcel wiki .The download for the current version 1.8.1 consists of a zip archive, which contains a directory tree 'PHPExcel-1-8-1' that looks like:

Classes/
  PHPExcel/
    ...
  PHPExcel.php
Documentation/
Examples/
...

We only need the Classes directory. Copy that directory to a suitable location in the web branch on your web server, for instance to the 'lib' directory in that branch. So if the root of your server web branch $_SERVER['DOCUMENT_ROOT'] is /var/www/html, then the Classes directory should be copied to /var/www/html/lib/Classes, making it look like:

/var/www/html/
  administrator/
  ...
  components/
  ...
  lib/
    Classes/
      PHPExcel/
        ...
      PHPExcel.php
  libraries/
  ...

Obviously this list just shows a few directories that should be familiar to you after studying the Joomla tutorials.

22.3 The changes

22.3.1 Files:

  • README.md
  • helloworld.xml

Again, these files have been updated to reflect version info.

22.3.2 admin/views/helloworlds/view.html.php

This view has been extended to show an additional button on the 'HelloWorld' administrator page. This button is to start the Excel export for the selected records (items). It works in the same way as the button for the csv export like explained in the previous section of this tutorial.

22.3.3 admin/controllers/helloexport.raw.php

Pushing the button results in a call to the 'exportxls()' function of this controller. It operates similarly to the exportcsv() function. The first steps are the same, up to and including retrieving the records from the database into the $content array.

The remainder of the function embeds the data in an Excel layout, just like the data in the previous example was embedded in a csv layout. This is described in the PHPExcel documentation, and this tutorial is loosely based on the example 01simple-download-xlsx.php in the PHPExpress 'Examples' directory.

Finally note that an include statement is added to the start of this controller:

require_once $_SERVER['DOCUMENT_ROOT'].'/lib/Classes/PHPExcel.php';

This statement loads the PHPExcel base class from PHPExcel.php , and assumes that you indeed installed PHPExcel in the lib/Classes directory on your webserver.

22.4 Source files for this step