How to use PHPExcel correctly with Symfony 2
Asked Answered
J

6

16

I need to use PHPExcel with a Symfony2 project. Anyone know how to set up the project correctly to use the library? Should i put it in the vendor directory? What should be changed in the configuration files etc?

Jocko answered 19/6, 2011 at 14:9 Comment(0)
T
5

If you are using composer to manage your project, you can just change the composer.json file:

"autoload": {
    "psr-4": {
        "": "src/",
        "": "vendor/phpoffice/phpexcel/Classes/"
    },
    "classmap": [
        "app/AppKernel.php",
        "app/AppCache.php"
    ]
},

Then add

use PHPExcel;
use PHPExcel_IOFactory;

to your controller file, and you can use the PHPExcel like this:

$objPHPExcel = new PHPExcel();

Hope it helps.

Targe answered 1/6, 2017 at 2:28 Comment(1)
Yep, this is the modern way. In 2011 things were a bit different :)Jocko
A
14

Actually, to do it right you need to follow next steps:

  • Edit your deps file and add dependency from the PHPExcel
[PHPExcel]
git=http://github.com/PHPOffice/PHPExcel.git
target=/phpexcel
version=origin/master
  • Run php bin/vendors install in order to install all missing dependencies (PHPExcel in our case)

  • Update prefixes section in app/autoload.php:

$loader->registerPrefixes(array(
    // ...
    'PHPExcel'         => __DIR__.'/../vendor/phpexcel/Classes',
));
  • Done. Now, you can use it in your bundle's controller (code based on PHPExcel example from Tests/01simple-download-xls.php):
<?php
namespace Demo\MyBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use PHPExcel;
use PHPExcel_IOFactory;

class DemoController extends Controller
{
   public function demoAction()
   { 
       $response = new Response();

       // Create new PHPExcel object
       $objPHPExcel = new PHPExcel();

       // Set document properties
       $objPHPExcel->getProperties()->setCreator("Me")
                   ->setLastModifiedBy("Someone")
                   ->setTitle("My first demo")
                   ->setSubject("Demo Document");
       // Add some data
       $objPHPExcel->setActiveSheetIndex(0)
                   ->setCellValue('A1', 'Hello')
                   ->setCellValue('B2', 'world!')
                   ->setCellValue('C1', 'Hello')
                   ->setCellValue('D2', 'world!');
       // Set active sheet index to the first sheet
       $objPHPExcel->setActiveSheetIndex(0);

       // Redirect output to a client’s web browser (Excel5)
       $response->headers->set('Content-Type', 'application/vnd.ms-excel');
       $response->headers->set('Content-Disposition', 'attachment;filename="demo.xls"');
       $response->headers->set('Cache-Control', 'max-age=0');
       $response->prepare();
       $response->sendHeaders();
       $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
       $objWriter->save('php://output');
       exit();
   }
}
Alexine answered 4/11, 2012 at 19:31 Comment(5)
just add $response = new Response(); at the beginning of the function and include use Symfony\Component\HttpFoundation\Response;Alexine
I would never use "new" operator in Symfony2 controller as basically - you are saying - I will never unit test this controller, nor I'm giving my co-workers giving a chance to test this. This will work, but it's a bad, bad practiceImmunotherapy
@Immunotherapy Can you provide the best practice solution?Alexine
@Alexine Sure, sorry, my bad;) Wrap PHPExcel in a service class and the use $this->get('my.phpexcel_service') in the controller to access that service. Then you can inject this service to other services as well...and so on... and all is easy to test/mock. Hope it helped at least a bit.Immunotherapy
@Alexine Worth a read (even a few times): Symfony2 Services DocsImmunotherapy
P
11
  1. Copy the library to your vendors directory.
  2. Configure autoloader in your bootstrap file:

    $loader->registerPrefixes(array(
        // Swift, Twig etc.
        'PHPExcel' => __DIR__ . '/../vendor/phpexcel/lib/PHPExcel'
    ));
    
  3. That's all.

Phonolite answered 19/6, 2011 at 18:15 Comment(4)
I have the same problem, could you explain your solution a bit more? If I try to initialize the PHPExcel class in my controller, I get a "class not found"...Toque
Thank you - but how can I init the PHPExcel class in my controller - is a "new PHPExcel" sufficient or do I have to use a namespace?Toque
PHPExcel doesn't support namespaces, it's defined in global namespace. Use \PHPExcel.Phonolite
Someday (hopefully) PHPExcel will be able to drop support for PHP 5.2 and set PHP5.3 as a minimum version, and then we will be able to use namespaces; but with over 50% of the userbase still running 5.2 servers we can't make the change yet :(Sonyasoo
E
10

actually the best solution is to use https://github.com/liuggio/ExcelBundle. I tried to use @Crozin's solution but I was still getting an error about IOFactory::createWriter. Hope this helps, Simone

Encaenia answered 18/4, 2012 at 9:0 Comment(0)
H
7

As of Symfony 2.3, you can now do this:

...
"require": {
    ...
    "phpoffice/phpexcel": "dev-master"
    ...
},
...

Then just run composer update and dependencies will resolve automatically.

Or you can do composer require phpoffice/phpexcel:dev-master if you don't want to mess with the composer.json file.

Hoffer answered 4/6, 2014 at 18:58 Comment(0)
T
5

If you are using composer to manage your project, you can just change the composer.json file:

"autoload": {
    "psr-4": {
        "": "src/",
        "": "vendor/phpoffice/phpexcel/Classes/"
    },
    "classmap": [
        "app/AppKernel.php",
        "app/AppCache.php"
    ]
},

Then add

use PHPExcel;
use PHPExcel_IOFactory;

to your controller file, and you can use the PHPExcel like this:

$objPHPExcel = new PHPExcel();

Hope it helps.

Targe answered 1/6, 2017 at 2:28 Comment(1)
Yep, this is the modern way. In 2011 things were a bit different :)Jocko
V
2

With composer (since Symfony2.1) it's really easy, you only have to modify the composer.json.
You don't need to register the namespace anymore!

Only two things, to notice:

  1. refer to github tags, I only found a soltion with the package type
  2. when changing something in the composer.json related to the class autoloading stuff, you have to remove the whole directory in the vendor dir

Here is the related link: use PHPExcel with composer and Symfony2.2

Vatican answered 25/4, 2013 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.