Sunday, July 15, 2012

Adding PHPExcel PEAR Library in Shared Hosting Environment

You need to have the PEAR library installed in your shared host/server before this. If you haven't done so, you can check out my earlier post on how to do this.

The Steps I used:
  1. You can download the PHPExcel here. Choose the PEAR version. As of now, the current version is 1.77 and the file size for the .tgz file is 11.7MB.

  2. Extract the .tgz file. You'll see a PHPExcel.php and a PHPExcel folder. Like other PEAR add-ons, you just need to copy the PHP file and the folder to your PEAR root directory. You can find out the root directory during the installation of PEAR. You can also refer to my earlier post on this.

  3. Upload the above mentioned PHP file and its folder to your shared server.

  4. Test your PEAR PHPExcel library using the following codes:


    set_include_path('./RELATIVE_PATH_TO_YOUR/PEAR/' . PATH_SEPARATOR . get_include_path());

    $excel = new PHPExcel();
    $excel->setActiveSheetIndex(0); // select a worksheet
    $excel->getActiveSheet()->setTitle('Products'); // name the sheet
    $excel->getActiveSheet()->setCellValue('A1', 'Orange');
    $excel->getActiveSheet()->setCellValue('A2', '1.30');
    $excel->getActiveSheet()->setCellValue('B1', 'Apple');
    $excel->getActiveSheet()->setCellValue('B2', '2.10');
    $excel->getActiveSheet()->setCellValue('C1', 'Total');
    $excel->getActiveSheet()->setCellValue('C2', '=SUM(A2:B2)');

    // Save document in the Excel 2007 format
    $excelWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
    echo("Products.xlsx created!");


  5. Open the "Products.xlsx" with Excel to see if the xlsx file is fine as planned.

Note: If your PHP file above (to test the PHPExcel library), contains non-English character, you'll need to save it in non-BOM format preferably saved using Notepad++. Here's my post to address this fix.

As for the RELATIVE_PATH_TO_YOUR in red above, RELATIVE is the key. If you PHP file is in a subdirectory and your PEAR's root is in another subdirectory, you need to find a path to refer to PEAR. For example, if your testPHPExcel.php is in the /test directory and your PEAR is in /PEAR directory, you'll need this relative path such as ./../PEAR/.

You are done here! Enjoy!