4.5 (90%) 2 votes

You will follow these steps to Read/Write CSV File from Magento:

  1. Create class Magestore\Training\Model\CsvImportHandler.php
  2. Use other function to process the data which you want.
  3. Write the data to CSV

Hello everyone!

As you know, CSV file is the file type which Magento uses for the import data to database. You can import tax rate, product … by using the .csv file. If you build the extension, maybe you need this featured to quickly import data to the database. In this blog, I will show you how to read/write the data of CSV file by code.

Example, we have a .csv file:

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

-Read the data from CSV:

Step 1:

First, please create class Magestore\Training\Model\CsvImportHandler.php

$file: the file which you receive from the upload file form.

All function which you need to read/write the csv file are in the Magento\Framework\File\Csv class. After pass the argument $file (the file after you upload csv file to the server), and use the getData() function, you will receive the array which include all the row of this csv file.

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

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

Step 2:

After that, please use other function to process the data which you want.

-Write the data to CSV:

Step 3:

After processing the data which you receive from uploading csv file, you can write the data to csv:

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

$file: the path to the file which you want to write

$importProductRawData:  the data (array)

Hope all you guys can learn magento 2 easier with our series lesson.  The step I mention above is the shortest process for you to Read/Write CSV File from Magento. With this guide, you can manage the Read/Write CSV File in Magento 2 easily. Every store has a CSV File from Magento with many attributes.

Thank you for reading this post.

Thank you for reading this blog!

 

Your Magento website needs a powerful Magento ERP for stock control.

DON'T MISS THE CHANCE!

magento erp

How to Get Content from a UI Component
How to Insert New Tab into Customer Form in Backend Magento 2

Comments are closed.