使用带有SYMFONY3的EXCEL FILE在数据库中添加数据

时间:2017-04-28 15:28:04

标签: symfony

有没有人使用EXCEL FILE在symfony3的数据库中添加数据!谢谢!

1 个答案:

答案 0 :(得分:1)

几个月前,我有同样的问题。 我最后用函数this class编写了getArrayFromCsv()。 使用它,您所要做的就是将您的Excel文件保存为.csv,然后将文件传递给该函数,您将获得一个数据数组,以便您可以按照自己的意愿处理它们。

更多解释,您可以使用str_getcsv php函数将某些csv内容作为参数,或者fgetcsv如果您传递csv文件的资源实例。

然后,处理您的数据。

以下是使用该类作为依赖关系的fixture load()函数的示例;作为与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.
}