CSV export in Magento 2

Magento 2 has a CSV processor, that is being used to import and export product and customer related data.

For one of my project I had to generate a CSV of the information I received for a product(s) from an API and use the same CSV as an input file for updating the quantity of the product(s).

Below is the file,

<?php
/**
 * @author DecryptWeb
 * @copyright Copyright (c) 2020 DecryptWeb (https://www.decryptweb.com/)
 */

namespace DW\Interface\Model;

use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Filesystem\Io\File as CsvFile;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Framework\File\Csv;
use Magento\Framework\App\Filesystem\DirectoryList;

/**
 * Class ProductInventoryUpdate created
 */
class ProductInventoryUpdate
{
    /**
     * @var \Magento\Framework\File\Csv
     */
    protected $_csvProcessor;
    /**
     * @var \Magento\Framework\App\Filesystem\DirectoryList
     */
    protected $_directoryList;
    /**
     * @var \Magento\Framework\Stdlib\DateTime\TimezoneInterface
     */
    protected $_date;
    /**
     * @var \Magento\Framework\Filesystem\Io\File
     */
    protected $_filesystem;
    /**
     * @var \Magento\Framework\Filesystem\Driver\File
     */
    protected $_driver;
    /**
     * @var array
     */
    protected $response = [];

    /**
     * @param DirectoryList                                                  $_directoryList
     * @param Csv                                                            $_csvProcessor
     * @param \Magento\Framework\Stdlib\DateTime\TimezoneInterface           $date
     * @param \Magento\Framework\Filesystem\Io\File                          $_filesystem
     * @param \Magento\Framework\Filesystem\Driver\File                      $_driver
     */
    public function __construct(
        DirectoryList $_directoryList,
        Csv $_csvProcessor,
        TimezoneInterface $date,
        CsvFile $_filesystem,
        File $_driver,
    ) {
        $this->_directoryList                 = $_directoryList;
        $this->_csvProcessor                  = $_csvProcessor;
        $this->_date                          = $date;
        $this->_filesystem                    = $_filesystem;
        $this->_driver                        = $_driver;
    }//end __construct()


    /**
     * @param $productArray
     * @return string
     * @throws \Magento\Framework\Exception\FileSystemException
     */
    public function writeToCsv($productArray)
    {
        $fileDirectoryPath = $this->_directoryList
            ->getPath(DirectoryList::VAR_DIR) . '/' . 'apis';

        if (!$this->_driver->isExists($fileDirectoryPath)) {
            $this->_filesystem->mkdir($fileDirectoryPath, 0777, true);
        }
        $datetime = $this->_date->date()->format('Ymd_His');
        $fileName = 'catalog_product_'.$datetime.'.csv';
        $filePath = $fileDirectoryPath . '/' . $fileName;

        $data = [];

        $data[] = [
        'source_code',
        'sku',
        'status',
        'quantity',
        ];
        /* pass data array to write in csv file */
        foreach ($productArray as $k => $product) {
            $data[] = [
            $product['source_code'],
            $product['sku'],
            $product['status'],
            $product['quantity'],
            ];
        }
        $this->_csvProcessor
        ->setEnclosure('"')
        ->setDelimiter(',')
        ->saveData($filePath, $data);
        return $filePath;
    }//end writeToCsv()

}//end class

– Above will dynamically generate a file in a specified directory [root_directory]/var/apis/ along with the timestamp

Hope this is helpful

Leave a Reply

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

Scroll to top