is there anyone anyone who used EXCEL FILE to add data in data base with symfony3 ! thanks !
-
Welcome to stackoverflow, it would be better to share what you have tried and then people would be able to start helping you.Amr Eladawy– Amr Eladawy2017-04-28 16:16:18 +00:00Commented Apr 28, 2017 at 16:16
-
Yes. I frequently import excel data into a database. And I even export as well.Cerad– Cerad2017-04-28 17:08:46 +00:00Commented Apr 28, 2017 at 17:08
1 Answer
I had the same issue few months ago.
I ended up writing this class with the function getArrayFromCsv().
Using it, all you have to do is to save your excel file as a .csv, then pass the file to the function, and you'll get an array of your data so that you can process them as you wish.
More explained, you can just use str_getcsv php function with some csv content as parameter, or fgetcsv if you pass a resource instance of the csv file.
And then, process your data.
Here is an example of a fixture load() function using that class as dependency; as a way of using it with symfony:
public function load(ObjectManager $manager)
{
$this->onLoadStart($manager);//A custom processing to initialize the fixture object instance
$setLineKeys = function ($keysRow) {//A callback to redefine the keys of the obtained array of data
return $this->setLineKeys($keysRow);
};
$clients = CollectionUtil::getArrayFromCsv($this->getFileName(), NULL, NULL, NULL, $setLineKeys);//We read the file and put the data in an array structure
$noAddress = [];
foreach ($clients as $clientData) {// We process the array in order to build entities
foreach ($clientData as $key => &$value) {
$value = trim($value);
}
$client = (new Client())
->setName($clientData['name'])
->setAbbreviation(substr($clientData['abbreviation'], 0, 6))
->setBillable($this->isBillableGuess($clientData))
->setSector($this->getSector($clientData, $manager))
->setAddress($this->getAddress($clientData))
->setAccountingData($this->getAccountingData($clientData))
->setSite($this->defaultSite)
->setOrganization($this->defaultSite->getOrganization())
;
!$clientData['telephone'] ?:
$client->addPhone((new Phone($clientData['telephone']))->setPrimary(true))
;
!$clientData['email'] ?:
$client->addEmail((new Email($clientData['email']))->setPrimary(true))
;
!$clientData['fax'] ?:
$client->addFax((new Fax($clientData['fax']))->setPrimary(true))
;
if (NULL == $client->getAddress()) {
$noAddress[$clientData['abbreviation']] = $clientData['name'];
} else {
$this->buildCode($client);
$manager->persist($client);
}
}
$manager->flush();// We persist all the entities we just built.
}