How to export an entity as a CSV in Symfony?

后端 未结 2 2020
小蘑菇
小蘑菇 2021-01-03 14:06

I am using the following code to output a CSV but I am getting a blank screen when I run it. basically my confusion is with the DoctrineORMQuerySourceIterator as I am not un

相关标签:
2条回答
  • 2021-01-03 14:47

    A working example using the CsvWriter :

    $format = 'csv';
    $exportTo = 'php://output';
    $exporterWriter = '\Exporter\Writer\\' . ucfirst($format) . 'Writer';
    
    $data = $repository->createQueryBuilder('r')->getQuery();
    $fields = array('Last Name' => 'pLastName', 'First Name' => 'pFirstName');
    $source = new DoctrineORMQuerySourceIterator($data, $fields);
    $writer = new $exporterWriter($exportTo);
    
    Handler::create($source, $writer)->export();
    

    Sorry for the delay before answer your issue.

    0 讨论(0)
  • 2021-01-03 14:57

    The secound parameter of the DoctrineORMQuerySourceIterator is an array of property names like this:

    ['Column name in the output' => 'fieldName', 'Something' => 'address.street']
    

    As you can see in the source code it actually uses the Property Accessor component to access the data (you can find more examples there).

    If you want to export raw data form the db, I rocommend to use the PDOStatementSourceIterator or the DoctrineDBALConnectionSourceIterator instead as those are faster. The former requires a PDOStatement and the other requires a connection, a query and an array of prameters (you can see it in the linked source code) as constructor parameters.

    0 讨论(0)
提交回复
热议问题