在Symfony数据库中导入Excel数据

时间:2017-09-06 11:17:14

标签: php excel symfony

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

3 个答案:

答案 0 :(得分:1)

您可以使用fgetcsv PHP函数,例如here

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

答案 1 :(得分:1)

如评论中所述,您可以使用PHPExcel。使用composer

安装库
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,但为什么要打扰。同样易于阅读原始文件并为用户节省额外的一步。

答案 2 :(得分:0)

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

看看这个:docs

这里的示例显示了将您的表放入数据库是多么容易

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

试一试!