如何使用symfony2 excelbundle从excel文件中检索数据?

时间:2015-03-31 08:42:48

标签: php symfony bundle phpexcel

对于学校项目,我必须从用户上传的Excel文件中收集数据。我正在使用Symfony2并安装了一个我在knpbundles上找到的包,名为ExcelBundle。我读到要从Excel文件中收集数据,我应该使用phpExcel对象的createWriter方法。这就是我所做的,如下所示。

public function addContactsFromExcelAction(Request $request) {
    $uploadDir = '/var/www'.$request->getBasePath().'/uploads/';
    //die(var_dump($uploadDir));
    $file = $request->files->get('fichierExcel');
    $fileName = $file->getClientOriginalName();
    $fileSaved = $file->move($uploadDir,$fileName);
    $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($uploadDir.$fileName);
    $writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel2007');

}

但问题是,实际上,我真的不知道如何使用编写器从我的Excel数据表的单元格中收集数据。

拜托,有谁可以帮我实现目标?

1 个答案:

答案 0 :(得分:7)

您可以按此示例进行迭代:

public function xlsAction()
{
    $filenames = "your-file-name";
    $phpExcelObject = $this->get('phpexcel')->createPHPExcelObject($filenames);

    foreach ($phpExcelObject ->getWorksheetIterator() as $worksheet) {
        echo 'Worksheet - ' , $worksheet->getTitle();
        foreach ($worksheet->getRowIterator() as $row) {
            echo '    Row number - ' , $row->getRowIndex();
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
            foreach ($cellIterator as $cell) {
                if (!is_null($cell)) {
                    echo '        Cell - ' , $cell->getCoordinate() , ' - ' , $cell->getCalculatedValue();
                }
            }
    }
    }
}

更多样本here