CSV is a file format for easy data import-export, notably helpful in Magento to add products in bulk, migrate products, reviews import-export, inventories, customer data to transfer a large number of data between two programs, manage catalogs, customer data management, and much more.
Working with CSV files in Magento is very common. Developers often need to import CSV in Magento configuration, and read and extract its data. Similar to importing CSV in Magento configuration you can also add date and time picker in Magento configuration to provide admin with some settings related to it.
Now that we know how important CSV files are, let’s go ahead with the method to import CSV in Magento configuration. Follow the below code for successful implementation.
Method to Import CSV in Magento Configuration:
Add the below code in the system.xml file
<import translate="label"> <label>Import CSV</label> <frontend_type>import</frontend_type> <backend_model>extension/upload</backend_model> <sort_order>50</sort_order> <show_in_default>1</show_in_default> <show_in_website>1</show_in_website> <show_in_store>1</show_in_store> </import>
Create Upload.php file at app/code/local/Vendor/Extension/Model directory
class Vendor_Extension_Model_Upload extends Mage_Core_Model_Config_Data { public function _afterSave() { Mage::getModel('extension/import')->uploadAndImport(); } }
Create Import.php file at app/code/local/Vendor/Extension/Model directory
class Vendor_Extension_Model_Import extends Mage_Core_Model_Abstract { public function uploadAndImport() { if (empty($_FILES['groups']['tmp_name']['extension']['fields']['import']['value'])) { return $this; } $csvFile = $_FILES['groups']['tmp_name']['extension']['fields']['import']['value']; $io = new Varien_Io_File(); $info = pathinfo($csvFile); $io->open(array('path' => $info['dirname'])); $io->streamOpen($info['basename'], 'r'); $headers = $io->streamReadCsv(); if ($headers === false || count($headers) < 1) { $io->streamClose(); Mage::throwException(Mage::helper('extension')->__('Invalid CSV File')); } try { $count = 0; while (false !== ($csvLine = $io->streamReadCsv())) { if (empty($csvLine) || $csvLine[0] == '') continue; Mage::log($csvLine[0]); $count++; } Mage::getSingleton('core/session')->addSuccess( Mage::helper('extension')->__('Successfully imported ' . $count . ' record') ); } catch (Mage_Core_Exception $e) { Mage::throwException($e->getMessage()); } return $this; } }
Run the above code and easily read or extract data from the CSV files!
Thank You