Reading/Parsing Excel Spreadsheet using PHP

June 15th, 2008 | Save to del.icio.us now(0)

This is second article in the series of common PHP problems that a beginner faces. You can check the first article Warning: header data already sent.

In this tutorial we will see, how we can easily parse or read an Excel sheet and display the parsed data to user. Even though we are going to display the output, the other extension of this technique is that we can parse an excel sheet filled with data, in set format, and convert it into SQL statement and insert the data into database. Now this is an easy task on an windows based server, to do the same thing in Linux we need to use some other libraries.

This tutorial assumes that you know PHP.

So let’s get into the details, PHP-ExcelReader is used for parsing the excel sheet.

Example Spreadsheet that we are going to parse

First of all download the PHP-ExcelReader from SourceForge, if you PEAR configured properly or you can download the files Excel Reader from which I have removed the PEAR dependency (note: this is a bad practice, I only use this in my DEV environment for simple parsing and testing, please do not use this file in production environment).

require_once 'reader.php';

I just included the class file.

Now we will use following function for parsing the file, This function basically returns the data parsed from the excel sheet in an associative array. Off-course you have to remember that it is just a quick function to get the job done in DEV environment and you should not use it in production environment, without suitable modifications.

function parseExcel($excel_file_name_with_path)
{

    $data = new Spreadsheet_Excel_Reader();
    $data->setOutputEncoding('CP1251');
    $data->read($excel_file_name_with_path);

    $colname=array('NAME','SKU','PROD GROUP','WAREHOUSE CODE','DATE','LENGTH','WIDTH','COLOR','WEIGHT LB','PACKAGING','COST','RETAIL','WHOLESALE','SHIPPING COST','QUANTITY','MIN INV','MAX INV','DESC');
    $startloging=false;
    $k=0;

    for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {

        for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {

            if($data->sheets[0]['cells'][$i][$j]=='NAME')
            {
                $startloging=true;
                break;
           }
           if($startloging)
            {
                $product[$k-1][$j-1]=$data->sheets[0]['cells'][$i][$j];
                $product[$k-1][$colname[$j-1]]=$data->sheets[0]['cells'][$i][$j];

            }

        }

        if($startloging)
        {

            $k=$k+1;

        }

    }

    return $product;

}

In first line we initialize the Spreadsheet_Excel_Reader, then we set the output encoding.

Finally we read the Excel file using read method of Spreadsheet_Excel_Reader class. This basically completes the process of reading the excel spreadsheet. Simple isn’t it?

Rest of the logic is basically parsing the output array of spreadsheet class, to more user friendly and easy to understand array.

The first FOR loop is counting the rows in spreadsheet, while second FOR loop is counting the number of columns in each row.

if($data->sheets[0]['cells'][$i][$j]=='NAME')

This condition is used to find the right row and column while parsing the data array. This ensures that we only return the relevant data from the excel sheet and not everything. In your case replace ‘NAME’ with the name of the first column in your spreadsheet.

Are you satisfied with your knowledge? No, then spent 15 minutes every day on PHPCamp.net a knowledge sharing website for our own PHP community

Once we figure out the correct row( from where we need to pick the data) we save it in both the numeric array and also as associative array.

Here is a variation of this function, where our excel sheet does not have any column name mentioned.

Second Example of Spread Sheet

function parseExcel($excel_file_name_with_path)
{

    $data = new Spreadsheet_Excel_Reader();

    // Set output Encoding.

    $data->setOutputEncoding('CP1251');

    $data->read($excel_file_name_with_path);
    $colname=array('id','name');

    for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
          for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {

                $product[$i-1][$j-1]=$data->sheets[0]['cells'][$i][$j];
                $product[$i-1][$colname[$j-1]]=$data->sheets[0]['cells'][$i][$j];

        }

    }

    return $product;

}

If you know some other alternatives please share.

Related posts

  1. Joomla 1.0.x : How it works
  2. How to get Latitude/Longitude from an address (or Geocoding ) using PHP
  3. Simple Way To Add Global Exception Handling In CodeIgniter
  4. Installing PEAR and PHPUnit on WAMP and Windows 7
  5. 5 key skills of a successful web application developer

Wondering what to do next?


(Search web development related contents)


69 Responses to “Reading/Parsing Excel Spreadsheet using PHP”

  1. June 16, 2008 5:15 pm Binny V A says

    My general advice to client is to use the CSV format instead of Excel files for import/export purposes. CSV has native PHP support.

    But some clients insist on using Excel – in those cases, this will come in handy.

  2. June 16, 2008 11:15 pm roScripts - Webmaster resources and websites says

    Reading/Parsing Excel Spreadsheet using PHP…

    This is second article in the series of common PHP problems that a beginner faces You can check the first article Warning header data already sent In this…

  3. July 9, 2008 10:22 am PHP : Dead Easy Excel Export | Edmonds Commerce Blog says

    [...] to Excel by configuring the MIME Type Profile Option Power your PHP Business Logic with Excel Reading/Parsing Excel Spreadsheet using PHP Bookmark this [...]

  4. July 10, 2008 2:28 pm Jasonwoon says

    Anyhow i tried use the reader.php but i got this error

    Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 512 bytes)
    any idea how to direct read it without puting the data into arrays? cos my excel file size is 70MB consist of 114 columns and 29,000 rows of datas. Pleaseeeee Help!!

  5. July 22, 2008 1:06 am | 8 Jam 27 Menit | Catatan says

    [...] melakukan konversi membuat diri saya mampir ke blog salah satu sahabat saya di PHPUG, lalu mampir kemari dan akhirnya saya dapatkan Excel Reader yang sudah bersih dari PEAR Library. Setelah itu, saya buat [...]

  6. July 23, 2008 5:23 am parvin gaikwad says

    i want to read excel esv file i am able to read it but

    i have some formula’s in my excel csv file i want to read the data with

    output of given formula but i can,t read it..

    the output come with formula

  7. August 20, 2008 3:14 pm nhojnivron says

    guys anyone here have a fix on the date problem? coz the date output is like this 00/0606/08080808 instead of 08/21/2008… i tried different encodings though TIA

  8. August 24, 2008 8:43 pm eltioloco says

    Was there a solution for the memory error…i have a small file 3.5 mb it will not work, but when i cut in half…runs fine.

    I made the date updates and GetInt4 update but that did not help.

    but my file will keep growing…i plan to have a 15 mb file when its all compile.

    If you find a solution for the 70mb file please share the info.

  9. September 15, 2008 7:50 am Galder says

    Thank you very much for your advice, Binny VA. I have applied your advice, say no to excel, and it was working properly in 5 minutes with csv.

    Thank you to everybody!

  10. October 7, 2008 7:48 am vineeth says

    how to install php excel reader. i have xampp folder
    so where i put this new packages inside of this xampp
    anyone pls help me

  11. October 21, 2008 7:41 am Gauttam says

    I use this code for upload a excel file but in my code fisrt i give upload a master xls file on local machine then user add the data and then upload this save file so at that time it’ll give error this file is not readable.and i make another file on local machine it’ll upload so it’s not give an error readable.it’ll easly uploaded so what to do for that?
    pls give reply as soon as possible

  12. October 21, 2008 8:35 am Amit Kumar Singh says

    @gauttam you need to set the file permissions properly.

  13. October 21, 2008 9:30 am Gauttam says

    ya i set all the permission for the file but then also not able to upload that file i already chk my tmp folder rights and file also but not able to upload http://ganesh/fidility/sponsors/accountusers just go on this link user name & pwd gautampatel/passwd. I think tmp folder has full control otherwise it’ll not give to upload the file

  14. October 21, 2008 9:36 am Gauttam says

    When i download master file and then open that file and save as on my local machine so at that time also able to upload.Otherwise it’ll give error for the file is Tmp\php741.tmp is not readable

  15. October 21, 2008 9:39 am Gauttam says

    above link is on my local machine this is server link

    http://www.giuliopia.com/winepoints/sponsors/accountusers

    user_id and password both are same in above comment

  16. October 21, 2008 10:59 pm Marc says

    MY problem with the phpexcelreader is that it can’t read the temporary file PHP uploads via a web form. I don’t want to save every dang file being uploaded. I just want the parsed content and then to move on. Fails. :(

  17. December 9, 2008 6:31 am anson says

    MY problem with the php excel is that it can’t write picture into the appointed excel file via a PHP web form. And I don’t know how to convert excel into pdf via PHP,Pls help me !
    mail:anson.wu@valence.com

  18. January 1, 2009 12:50 pm Rakesh Kumar Nautiyal says

    I have downloaded the excel reader and putted it on my local web server
    I is working properly but when I was uploaded this on webserer It is showing two type of err The filename Sql2Excel.xls is not readable
    But reading and fetching the records on localhost server. How can Improve and solve the problem with the script.

  19. January 1, 2009 1:29 pm Amit Kumar Singh says

    @rakesh please check that actual file name on the erver and file name you specified in the script are same(it is case-sensitive)

  20. January 2, 2009 10:04 am Rakesh Kumar Nautiyal says

    Please Tell me which file name either it is excel file name or other
    I am giving the path and here it the the script and the problem.
    http://digital-product-retailer.com/excel/xls2mysql_step1.php

    http://digital-product-retailer.com/excel/xls2mysql.php

  21. January 2, 2009 10:29 am Rakesh Kumar Nautiyal says

    function str_database_name($str)
    {
    $str=strtolower(strtr($str,”*()!$’?: ,&+-/.ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ”,
    “—————SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy”));
    return $str;
    }
    what is this function

  22. January 12, 2009 12:01 am PatrickMc says

    biterscripting tends to be very usful when it comes to parsing CSV (Command separated values) files, or just parsing/reporting in general (web logs, excel files, html documents, xml documents, …). They have posted an excellent sample script at http://www.biterscripting.com/Download/SS_CSV.txt. You can download biterscripting free at http://www.biterscripting.com . Hope this helps.

    Patrick Mc

  23. January 16, 2009 12:11 pm pankaj kamble says

    hi sir
    i know the how data show in excel but my problem is how i will show IMAGE in excel sheet.do u have any way

  24. February 19, 2009 12:52 pm Srinivas says

    Hi i am creating a spreadsheet when client clicks on a button but when i try to upload the file for reading the contents using “reader.php” i get the following error:

    “The file name template.xls is not readable” i think its going to line # 171 in reader.php page.

    please help me out in this issue Thanks in advance.

  25. March 10, 2009 4:48 am thuclh says

    @ Srinivas : I sure your directory of the xls file is not true.you need to set the directory again? Examples : in my applycation,the xls file in helpers folder in a com_sim component of Joomla.But the command is $data->read(‘components/com_sim/helpers/hello.xls’);

  26. March 19, 2009 1:41 am TrialandError says

    Any solutions to the Date Error.

    My date also shows in the following way.

    00/1818/0909 when it should be 3/18/09

    i’ve tryed the updates, but no luck.

    thanks

  27. March 24, 2009 4:32 am Rakesh Kumar Nautiyal says

    Please guide me how can improve my website for the users. As this is tutorial site.

    Rakesh

  28. May 23, 2009 12:41 am Deep says

    While I am trying to upload a xls file after downloading and editing it, I am getting an error “The filename is not readable”. But if I copy the same content in a new xls and upload it,it’s getting uploaded successfully. I am using Mac and Safari.

  29. May 23, 2009 12:44 am somdip says

    I am getting a error “The filename is not readable” while uploading a exel file after downloading and editing it. But if a paste the content in a new excel the error doesn’t come. Please help.

  30. May 23, 2009 12:45 am somdip says

    Using Mac and Safari

  31. May 26, 2009 3:47 pm Ameen Raza says

    Hi,
    I am working on php 5 I tried the phpExcelReader,i also tried the example files with the downloaded directory and the above tutorial code but it simply didnt work..i dont see any error or any sort of info on the browser that why it didnt work..
    any help is appreciated

    Regards,

  32. May 26, 2009 5:49 pm Amit Kumar Singh says

    well, without error message it is hard to help, but may be you can try to see if path to xls file is correct.

  33. May 27, 2009 4:08 am somdip says

    Still facing the problem. Has anybody got the solution??

  34. June 12, 2009 3:22 pm Nishit.M.V says

    Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 33030145 bytes) in D:\xampp\htdocs\testexcel\Excel\oleread.inc on line 172

    Why do i get this when i run the example script

  35. June 23, 2009 9:04 pm Daniel Malikov says

    Thank you very much for this article.

    | I have removed the PEAR dependency: this is a bad practice

    Why is it bad practice?

  36. August 28, 2009 11:25 pm Fernando says

    Thanks for the article, is very usefuly. I have the “is not readable” error and i fix it in this way:

    i have uploaded file in webform and when call to the Spreadsheet_Excel_Reader read method send this argument $_FILES["myFile"]["tmp_name"] and doesn’t work, i move the file into own directory in this way :

    $path = “data/” .$_FILE["file"]["name"];
    $data = new Spreadsheet_Excel_Reader();
    $data->setOutputEncoding(‘CP1251′);
    $data->read($path);
    }

    and works fine. I hope thats was we helpfully for you

    Regards

  37. September 4, 2009 12:22 am shahil says

    hello people,

    please use “tmp_name” as the second array parameter.

    for example :-
    $data->read($_FILES['excelfile']['tmp_name']);

    so it will get the location of where the file is temporarily stored on server.

    thanks.

  38. September 28, 2009 9:40 am Vickykoko says

    Hi,
    i have the same error. like this
    “While I am trying to upload a xls file after downloading and editing it, I am getting an error “The filename is not readable”. But if I copy the same content in a new xls and upload it,it’s getting uploaded successfully.”
    i use many method,but i can’t solution this question,i also use ” ‘tmp_name’ as the second array parameter”,but can’t solution.

    please help !!

  39. October 1, 2009 5:33 am kalpan says

    Thanks for sharing.

    firstly I can’t switch to csv. My problem is in my excel file i have data in different languages (German, Italian, Spanish, Chinese, Japanese, Russian etc…) I am not able to read it all at once.

    I tried using different encoding mechanism but didnt work.

    Anyone????

  40. December 15, 2009 10:27 am rochmadi says

    I have a problem with the link cell, its data is not retrieved and displayed.

    Please help.

  41. January 6, 2010 5:14 pm Marco says

    Thanks for sharing this.Right now, I have problems importing an excel file with keywords. I will try to execute this code.

  42. March 13, 2010 8:01 pm Techie Talks says

    Cool Coding, thank you for helping me out with this problem…

  43. April 18, 2010 10:15 am Parse (Read) Excel Spreadsheet from PHP « Expertester says

    [...] Parse (Read) Excel Spreadsheet from PHP .xls : http://amiworks.co.in/talk/readingparsing-excel-spreadsheet-using-php/ [...]

  44. April 18, 2010 10:31 am Parse Excel document from PHP « My CS231 says

    [...] .xls : http://amiworks.co.in/talk/readingparsing-excel-spreadsheet-using-php/ [...]

  45. April 29, 2010 1:42 pm Schnuppi says

    What about more than 1 sheet? i have an XLS and only want to parse the content of the second excel-sheet. how to do this?

  46. May 21, 2010 9:45 pm Marco Barcelo says

    I have more than one table im my excel sheet
    (foreign key relation) and I want UPDATE or
    INSERT my data. In this case a lot of coding
    is required. I have read in other thread about
    dbtube.org. It is a grahpical editor for imports.
    Worth a look.

    marco

  47. May 29, 2010 7:59 am gar says

    I get this: 40087.00 for 10.01.09, any ideas?

  48. June 18, 2010 1:38 pm Snehasis Mohapatra says

    Hello,

    I am getting problem while Importing an XLS file which is exported.
    Procedure
    ===========
    1) I exported an xls.
    2) Save that file locally.
    3) Import the same XLS generating error that its unreadable.
    4) I copy the content and make a new xls manually and import and it works.

    Can u please explain why the same exported file is not unreadable.

    Thanks.

  49. July 8, 2010 2:50 pm Alex says

    I get this: 40087.00 for 10.01.09, any ideas?

    Does anyone know how to put the “correct” date format?

  50. July 17, 2010 3:09 am Bill says

    It works great with .XLS files, but doesn’t like the new Excel 2007 .XLSX format. Is that correct? Are there any plans to update phpExcelReader to work with 2007 files?

  51. July 19, 2010 9:51 pm Pritam says

    Hi,

    I need to extract an image from excel sheet and want to save it to local / application folder. How I can achieve this functionality?

    Regards,
    Pritam

  52. August 26, 2010 2:45 pm Sameer says

    Hi,
    You write very good script,but why we add two if condition for var ‘$startloging’.we can add the ‘$k=$k+1′ in one if loop.
    Can it possible to make the one array for each row? Not like the each column & row.

    Have dream day

  53. August 26, 2010 2:49 pm Sameer says

    Hi,
    I made new code for each row wish array.

    for ($i = 1; $i sheets[0]['numRows']; $i++)
    {

    for ($j = 1; $j sheets[0]['numCols']; $j++) {

    if($data->sheets[0]['cells'][$i][$j]==’Category Name’)
    {
    $startloging=true;
    break;
    }
    if($startloging)
    {
    $product[$i][$j-1]=$data->sheets[0]['cells'][$i][$j];
    $product[$i][$colname[$j-1]]=$data->sheets[0]['cells'][$i][$j];
    $k=$k+1;
    }

    }

    }
    Have dream day

  54. September 7, 2010 8:42 pm Blogalfin: Export file excel ke database mysql | says

    [...] dengan programming, disini saya menggunakan library class excel to mysql. silakan bisa di download Disini .  Cukup beberapa langkah mudah [...]

  55. September 23, 2010 10:36 pm sowmya says

    Hey thanq so much for the code…this helped me a lot for my work…THanks again

  56. November 30, 2010 12:13 am Carbontax says

    The unreadable file problem. That error message is generated because of the read function in oleread.inc file. on about line 55 we see that all errors are given the value of “1″. This means that all errors are reported as “unreadable file” even when the file is readable.

  57. December 29, 2010 4:17 pm omkar says

    its really work…

  58. February 5, 2011 12:38 pm Monu says

    It shows me following error
    Fatal error: Allowed memory size of 94371840 bytes exhausted (tried to allocate 71 bytes)in excel_reader/first_test/oleread.inc on line 133

  59. March 30, 2011 6:26 pm Rajesh says

    I need to extract excal sheet data and save it to database

    plese help me to extract data form an excel file containing more than one sheets

  60. April 13, 2011 1:28 am Mohammed says

    I want to read an excel file from a web directory to a localhost please help me with how to specify the path. I already tried this …. $data = new Spreadsheet_Excel_Reader(“www.domain.com/excel/$address”.”.xls”);

  61. July 3, 2011 2:31 pm Mujahid says

    I have a few columns which have optional values and hence can be empty, how can i check that while inserting, it is giving the error
    “Notice: Undefined offset: 2..” 2 would be the column number where that particular cell is empty. plz its a little urgent

  62. July 15, 2011 9:10 pm John Congdon says

    I hope this helps someone. I created a patch for Excel/reader.php that fixed the date fields in my situation. Learn more here:

    http://www.johncongdon.com/php-excelreader-php-date-format-error/

    Please make a backup of your version before attempting to use this patch, I don’t want to be responsible for bad things happening… :)

  63. July 20, 2011 1:19 pm Aman Nagra says

    Assigning the return value of new by reference is deprecated in D:\xampp\htdocs\countrylife\excelsheet_reader\reader.php on line 124

    getting this error when i downloaded reader.php, am using php5

  64. July 23, 2011 6:20 pm Jacob says

    is there a way to convert xls files to csv via php?
    i’d like to read an excel file and i’ve heard that reading csv files via php is far more simpler

  65. July 23, 2011 6:23 pm Jacob says

    could you tell me any way to convert xls files into the csv format…
    i want to read an xls file and have heard that reading a csv file is simpler….

  66. August 23, 2011 7:51 pm shyam says

    i am also having the same issue: Fatal error: Allowed memory size of 94371840 bytes exhausted.

    someone please suggest me if we need to install some special package or something.

    Please help or email me at => shyamji.gupta@netsmartz.net

  67. October 7, 2011 6:48 am Alex D says

    for the memory problems,try this.
    ini_set(‘memory_limit’, ‘-1′);

  68. October 7, 2011 2:25 pm Andris says

    Can I read the file. xls spreadsheet was given a password ??
    Please Help me..
    ‘^^

  69. January 10, 2012 3:34 pm Programatically Import Downloadable Product from Excel Spreadsheet « jMP Maniac says

    [...] used the following Excel Parser, to read the data from the [...]

Trackback URI | Comments RSS

Say Something, and Be Counted

Name (required)

Email (required)

Website

Speak your mind