【问题标题】:How to read a uploaded file ($_FILE) with Spout如何使用 Spout 读取上传的文件 ($_FILE)
【发布时间】:2020-09-01 09:35:56
【问题描述】:

我正在尝试创建一个页面,用户可以在其中上传格式正确的 Excel 文件(在手册中描述)并让文件插入到数据库中。

我认为一旦 Spout 可以读取文件,我就可以将文件插入数据库,但该部分不起作用。有人能帮我吗。

编辑:如果有问题,这个程序所在的服务器是共享的。

提前致谢,

荷兰人

代码:

// (1) FILE CHECK
// * HTML file type restriction can still miss at times
if (!isset($_FILES['upexcel']['tmp_name']) || !in_array($_FILES['upexcel']['type'], [
  'text/x-comma-separated-values',
  'text/comma-separated-values',
  'text/x-csv',
  'text/csv',
  'text/plain',
  'application/octet-stream',
  'application/vnd.ms-excel',
  'application/x-csv',
  'application/csv',
  'application/excel',
  'application/vnd.msexcel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
])) {
  die("Invalid file type");
}

require_once "../database.php";
require_once '/src/Spout/Autoloader/autoload.php';


use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;

$reader = ReaderEntityFactory::createReaderFromFile($_FILES['upexcel']['tmp_name']);

$reader->open($_FILES['upexcel']['tmp_name']);
foreach ($reader->getSheetIterator() as $sheet) {
    foreach ($sheet->getRowIterator() as $row) {
        // do stuff with the row
        $cells = $row->getCells();
        echo "</br> Hello" .$cells;
    }
}

$reader->close();

【问题讨论】:

  • 你有什么错误吗?
  • 另外注意Spout只支持XLSX格式,不支持旧的XLS。您的问题中列出的一些 mime 类型是指 XLS(例如“application/vnd.msexcel”)。所以 Spout 将无法读取给定的文件。您的代码是否适用于 CSV 文件?

标签: php spout


【解决方案1】:

我正在使用 Spout,但我遇到了同样的错误,我这样做了,如果你处理文件是 .xlsx 类型,它就可以工作。

代码:

$file = $_FILES['upexcel'];
$tmpName = $file ['tmp_name'];    
$reader = ReaderEntityFactory::createXLSXReader();
$reader ->open(tmpName);

这个代码是一个例子,你只需要改变这个:

$reader = ReaderEntityFactory::createReaderFromFile($_FILES['upexcel']['tmp_name']);

为此:

$reader = ReaderEntityFactory::createXLSXReader();

【讨论】:

    猜你喜欢
    • 2016-11-10
    • 2015-12-22
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 2014-10-10
    相关资源
    最近更新 更多