How to Read and write CSV file from Magento 2 platform?

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

  1. Create Class Webnexs \ Training \ Model \ CsvImportHandler.php
  2. Use other functions to process the 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 importing 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 with a few steps.

Facing trouble with your eCommerce website? Move to Magento marketplace, that actually scale better!!!

Example, .csv file:

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

How to Read and write CSV file from Magento 2?

Step 1:

First, form the Class Webnexs \ Training \ Model \ CsvImportHandler.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) {






$ 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 includes 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 a different function to process the information you need.

Write data to CSV:

Step 3:

After 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 2.

Click here to start building an online store with a Magento platform with 300+ features.

Read and write CSV file from Magento 2



, ,



Leave a Reply

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