2016-06-14 77 views

回答

3

您可以像在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. 
    } 
}