Ich habe CSV-Datei hochladen, aber Problem ist ich nicht wissen, wie Daten von hochgeladenen CSV-Datei in Magento2 lesen. Bitte helfen Sie mir, jemand. Vielen Dank im Voraus.Magento2 lesen hochgeladen CSV-Datei
0
A
Antwort
3
Sie können das tun, wie Sie in Magento 1 tun könnten. In Magento 1 würden Sie new Varien_File_Csv
verwenden, aber in Magento 2 können Sie das gleiche mit \Magento\Framework\File\Csv
tun. Sie können den folgenden Code verwenden.
In Ihrem __construct()
injizieren die folgenden Klassen:
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.
}
Dann können Sie es wie folgt verwenden:
// 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.
}
}