在Symfony数据库中导入Excel数据



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

如果您可以将Excel电子表格放入CSV格式,则可以处理一个非常好的软件包!

请看一下:http://csv.thephpleague.com/9.0/

这是他们的示例,显示将桌子放入DB

是多么容易
<?php
use LeagueCsvReader;
//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文件。

如评论中所述,您可以使用phpexcel。使用作曲家安装库

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,但是为什么要打扰。同样容易读取原始文件并为用户节省额外的步骤。

最新更新