Import Excel data in Symfony database

前端 未结 3 492
春和景丽
春和景丽 2021-01-14 10:15

I\'m working on a project where I need to import Excel data to my Symfony database. But the problem is that I don\'t know how to do that. I tried with ExcelBundle. The proje

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-14 10:56

    As mentioned in a comment you can use PHPExcel. Install the library using composer

    composer require phpoffice/phpexcel
    

    A typical reader might look something like

    class GameImportReaderExcel
    {
    
        public function read($filename)
        {
            // Tosses exception
            $reader = \PHPExcel_IOFactory::createReaderForFile($filename);
    
            // Need this otherwise dates and such are returned formatted
            /** @noinspection PhpUndefinedMethodInspection */
            $reader->setReadDataOnly(true);
    
            // Just grab all the rows
            $wb = $reader->load($filename);
            $ws = $wb->getSheet(0);
            $rows = $ws->toArray();
    
            foreach($rows as $row) {
                // this is where you do your database stuff
                $this->processRow($row);
            }
    

    Call the reader class from your controller

    public function (Request $request)
    {
        $file = $request->files->has('file') ? $request->files->get('file') : null;
        if (!$file) {
            $errors[] = 'Missing File';
        }
    
        $reader = new GameImportReaderExcel();
        $reader->read($file->getRealPath());
    

    That should get you started. And yes you could convert to csv but why bother. Just as easy to read the raw file and save your users an extra step.

提交回复
热议问题