0
我已经上传CSV文件,但问题是我不知道如何读取Magento2中上传的csv文件的数据。 请帮助我的人。 在此先感谢。Magento2读取上传的csv文件
我已经上传CSV文件,但问题是我不知道如何读取Magento2中上传的csv文件的数据。 请帮助我的人。 在此先感谢。Magento2读取上传的csv文件
您可以像在Magento 1中那样做。在Magento 1中,您可以使用 new Varien_File_Csv
,但在Magento 2中,您可以使用\Magento\Framework\File\Csv
。您可以使用下面的代码。
在你__construct()
注入以下类别:
protected $_fileCsv;
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Magento\Framework\Module\Dir\Reader $moduleReader,
\Magento\Framework\File\Csv $fileCsv
) {
$this->_moduleReader = $moduleReader;
$this->_fileCsv = $fileCsv;
parent::__construct($context); // If your class doesn't have a parent, you don't need to do this, of course.
}
然后你可以使用它像这样:
// This is the directory where you put your CSV file.
$directory = $this->_moduleReader->getModuleDir('etc', 'Vendor_Modulename');
// This is your CSV file.
$file = $directory . '/your_csv_file_name.csv';
if (file_exists($file)) {
$data = $this->_fileCsv->getData($file);
// This skips the first line of your csv file, since it will probably be a heading. Set $i = 0 to not skip the first line.
for($i=1; $i<count($data); $i++) {
var_dump($data[$i]); // $data[$i] is an array with your csv columns as values.
}
}