在Symfony数据库中导入Excel数据

我正在处理一个需要将Excel数据导入Symfony数据库的项目。 但问题是我不知道该怎么做。 我试着用ExcelBundle。 该项目是:用户必须使用表单button来发送他的Excel文件,我需要提取数据没有头来填充我的数据库。 你可以帮我吗 ?

正如在评论中提到的,你可以使用PHPExcel。 使用composer php安装库

composer require phpoffice/phpexcel 

一个典型的读者可能看起来像

 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); } 

从您的控制器调用读者类

 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()); 

这应该让你开始。 是的,你可以转换为CSV,但为什么打扰。 就像读取原始文件一样容易,并保存您的用户一个额外的步骤。

如果你可以把你的Excel电子表格转换成CSV格式,那么有一个非常好的软件包可以处理它!

看看这个: http : //csv.thephpleague.com/9.0/

以下是他们的示例,展示了如何将表格放入数据库

 <?php use League\Csv\Reader; //We are going to insert some data into the users table $sth = $dbh->prepare( "INSERT INTO users (firstname, lastname, email) VALUES (:firstname, :lastname, :email)" ); $csv = Reader::createFromPath('/path/to/your/csv/file.csv') ->setHeaderOffset(0) ; //by setting the header offset we index all records //with the header record and remove it from the iteration foreach ($csv as $record) { //Do not forget to validate your data before inserting it in your database $sth->bindValue(':firstname', $record['First Name'], PDO::PARAM_STR); $sth->bindValue(':lastname', $record['Last Name'], PDO::PARAM_STR); $sth->bindValue(':email', $record['E-mail'], PDO::PARAM_STR); $sth->execute(); } 

试一试!

你可以使用fgetcsv PHP函数, 这里就是一个例子。

Beford Excel文件必须更改为CSV文件。