Home » Frameworks, PHP

CodeIgniter: Reading Excel Files

20 April 2010 4 Comments

Reading Excel files in CodeIgniter is actually very easy once you have the right documentation. The first thing you will need to do is utilize the CodeIgniter “Upload” library and add in the Excel Reader library for reading the files. The documentation on the CodeIgniter website in regards to this Excel Reader library is missing some details in implementation. This tutorial will go through the steps of installing the Excel reader library and getting an example implementation working.

Step 1: Download the Excel Reader Library from CodeIgniter’s website.
http://codeigniter.com/wiki/Excel_Reader_Class/

Copy and paste the Excel_reader.php section into notepad or a text editor. Save the file in [CodeIgniter Folder]/system/application/libraries/ as Excel_reader.php

Step 2: Load the Library from your CodeIgniter Application
$this->load->library('excel_reader');

Step 3: Set the load path of the Excel file that has been uploaded
For example:
$uploadpath = "/var/www/uploads/test.xls";

Step 4: Run the Excel Reader Library
$this->excel_reader->read($uploadpath);
// Read the first workbook in the file
$worksheetrows =$this->excel_reader->worksheets[0];

Step 5: Set number of columns in your Excel file
$worksheetcolumns = 5;

Step 6: Run through the table and output the data
I’ve created a quick function that will go through the entire worksheet and output the data for testing.

echo "<table>";
foreach($worksheetrows as $worksheetrow)
{
      echo "<tr>";
     for($i=0; $i<worksheetcolumns; $i++)
    {
           // if the field is not blank -- otherwise CI will throw warnings
           if (isset($worksheetrow[$i]))
                 echo "<td>".$worksheetrow[$i]."</td>";
           // empty field
           else
                 echo "<td>&nbsp; </td>";
     }
     echo "</tr>";

echo "</table>";

This should get you going with reading Excel files in CodeIgniter.

4 Comments »

  • karen said:

    Brilliant, Thank you for the information. very useful

  • Egill said:

    Thank you, but how do I ever get special characters working? I’m Icelandic and special characters all turn into �.

  • Egill said:

    Sorry, sorry. Excel reader outputted in ISO format, I just had to utf8_encode($worksheetrow[$i]).

    Thank you!

  • rey1024 said:

    kok nda ada Excel_reader.php nya? boleh minta nda? thx

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.