【问题标题】:Import Excel data in Symfony database在 Symfony 数据库中导入 Excel 数据
【发布时间】:2018-02-14 20:43:02
【问题描述】:

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

【问题讨论】:

标签: php excel symfony


【解决方案1】:

如果您可以将您的 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();
}

试一试!

【讨论】:

  • 我现在使用 Symfony 5,对 foreach 进行必要的更改,但非常完美。谢谢
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    正如评论中提到的,您可以使用 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,但为什么要麻烦。阅读原始文件同样容易,并为您的用户节省了额外的步骤。

    【讨论】:

    猜你喜欢
    • 2019-08-10
    • 2017-07-05
    • 2011-06-24
    • 2011-04-13
    • 1970-01-01
    • 2016-02-09
    • 2020-02-27
    • 2020-02-24
    • 2017-03-09
    相关资源
    最近更新 更多