[英]Import Excel data in Symfony database
我正在一个项目中,我需要将Excel数据导入到我的Symfony数据库中。 但是问题是我不知道该怎么做。 我尝试使用ExcelBundle。 该项目是:用户必须使用表单按钮发送他的Excel文件,而我需要提取不带标题的数据来填充我的数据库。 你能帮助我吗 ?
如评论中所述,您可以使用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,但是为什么要打扰。 就像读取原始文件一样容易,并为用户节省了额外的步骤。
如果您可以将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();
}
试试看!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.