How to Read/write CSV file from Magento

Here the successive steps help you to Read/Write CSV file from Magento:

  1. Create Class Webnexs \ Training \ Model \ CsvImportHandler.php
  2. Use other function to process data you want.
  3. Write data to CSV

As you probably are aware, the CSV record is the kind of file that Magento utilizes for import information into the database. You can import the tax rate, item … utilizing the .csv record. In the event that you create an extension, you should bring information into the database rapidly. In this blog, I will tell you the best way to peruse/compose the CSV record’s information through the code.

Example, .csv file:

  • SKU, QTY
  • ABC,2
  • DEF,1

-Read the data from CSV:

Step 1:

First, form the Class Webnexs \ Training \ Model \ CsvImportHandler.php

<?php

namespace Magestore\Training\Model;

class CsvImportHandler

{

/**

* CSV Processor

*

* @var \Magento\Framework\File\Csv

*/

protected $csvProcessor;

public function __construct(

     \Magento\Framework\File\Csv $csvProcessor

)

{

     $this->csvProcessor = $csvProcessor;

}

public function importFromCsvFile($file)

{

     if (!isset($file['tmp_name'])) {

         throw new \Magento\Framework\Exception\LocalizedException(__('Invalid file upload attempt.'));

     }

     $importProductRawData = $this->csvProcessor->getData($file['tmp_name']);


     For every ($importProductRawData as $rowIndex => $dataRow) {

         \Zend_Debug::dump($dataRow);

     }

     die();

}

}

$ file: The file you obtain from the upload file format.

All the functionality you have read / write csv file are Magento \ Framework \ File \ Csv class. To send the argument $ file (file after uploading the csv file to the server), and use the getData () function, you will get the array that include all the sequences of this csv file.

$ dataRow [0]: CSV in the first row (title SKU, QTY)

$ dataRow [1], $ dataRow [2], …: the actual data you want

Step 2:

At that point utilize an different function to process the information you need.

Write data to CSV:

Step 3:

Subsequent to handling the information you get from transferring csv document, you can compose information to csv:

$ this-> csvProcessor-> saveData ($ file, $ importProductRawData);

$ file: The path of the file you want to write

$ importProductRawData: data (row)

The previously mentioned advances help you to Read/write in Magento

Last Update: March 6, 2019  

March 12, 2018   1324   Nandini Ramachandran    Operations    
Total 1 Votes:
0

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn