The Loginet\ExcelIOBundle
is responsible for importing and exporting data
from files with data validation.
The bundle uses the Symfony Validator service for data validation, and the PHPExcel Bundle for managing Excel files.
You need to write your own validators. These simple classes hold information about
how the data might look like (in ExcelIOValidatorColumn
objects. You have to specify the rules
(which are Symfony Validator constraints) for every column.
They must implement the Loginet\ExcelIOBundle\Validator\ExcelIOValidatorInterface
.
With the Loginet\ExcelIOBundle\Validator\AbstractExcelIOValidator
abstract helper class,
you can easily implement your own validator. For example:
(example) a simple UserValidator class:
<?php
namespace Loginet\ExcelIOBundle\Sample;
use Loginet\ExcelIOBundle\Validator\AbstractExcelIOValidator;
use Loginet\ExcelIOBundle\Validator\ExcelIOValidatorColumn;
use Symfony\Component\Validator\Constraints as Assert;
class UserValidator extends AbstractExcelIOValidator
{
public function addColumns()
{
$this->addColumn(
(new ExcelIOValidatorColumn())
->setName('user_name')
->addConstraint(new Assert\NotBlank())
);
$this->addColumn(
(new ExcelIOValidatorColumn())
->setName('user_type')
->notRequired()
->addConstraint(new Assert\Choice(['choices' => ['user', 'admin']]))
);
}
}
You can access the Excel Validator Manager through the loginet.excel_io_manager
service.
(example) Import data from file:
// this could be a service
$userValidator = new UserValidator();
$evm = $this->get('loginet.excel_io_manager');
$result = $evm->load('users.xls', $userValidator);
// the getAllRows() method gives you all rows, but there
// are also the getValidRows() and the getInvalidRows() methods
foreach ($result->getAllRows() as $row) {
// you can check the validity of the row
if ($row->isValid()) {
// you can access the field you need
$name = $row->getValue('user_name');
}
}
(example) Export data to file:
// this could be a service
$userValidator = new UserValidator();
// sample data we want to export
$data = [
(new ExcelIORow())
->setValue('user_name', 'John Doe')
->setValue('user_type', 'admin'),
(new ExcelIORow())
->setValue('user_name', 'Jane Doe')
->setValue('user_type', 'user'),
];
$evm = $this->get('loginet.excel_io_manager');
$result = $evm->dump($data, $userValidator);
// now we save it as a file
$result->toFile('users.xls');
// or alternatively we can create a streamed HTTP response object
$response = $result->toStreamedResponse();
// or create a response with proper headers
$response = $result->download('users.xls');