CSV import in Magento 2

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

In my earlier post I explained a way to generate a CSV.

I am explaining here a way to import a CSV to update inventory of the existing products.

<?php
/**
 * @author DecryptWeb
 * @copyright Copyright (c) 2020 DecryptWeb (https://www.decryptweb.com/)
 */
namespace DW\Interface\Model;

use Magento\Framework\App\State;
use Magento\ImportExport\Model\ImportFactory;
use Magento\ImportExport\Model\Import\Source\CsvFactory;
use Magento\Framework\Filesystem\Directory\ReadFactory;
use DW\Interface\Logger\Inventory\Logger;
use Magento\Framework\Filesystem\Io\File;

/**
 * Class Processor
 * @package DW\Interface\Model
 */
class Processor
{
    /**
     * @var State $state
     */
    private $state;

    /**
     * @var $importFactory
     */
    protected $importFactory;

    /**
     * @var $csvSourceFactory
     */
    private $csvSourceFactory;

    /**
     * @var ReadFactory
     */
    private $readFactory;

    /**
     * @var Logger
     */
    protected $_logger;

    /**
     * @var File
     */
    protected $_file;


    /**
     * Processor constructor.
     * @param State $state
     * @param ImportFactory $importFactory
     * @param CsvFactory $csvSourceFactory
     * @param ReadFactory $readFactory
     * @param Logger $logger
     * @param File $_file
     */
    public function __construct(
        State $state,
        ImportFactory $importFactory,
        CsvFactory $csvSourceFactory,
        ReadFactory $readFactory,
        Logger $logger,
        File $_file
    ) {
        $this->state            = $state;
        $this->importFactory    = $importFactory;
        $this->csvSourceFactory = $csvSourceFactory;
        $this->readFactory      = $readFactory;
        $this->_file            = $_file;
        $this->_logger          = $logger;
    }//end __construct()
    /**
     * @param string $import_path      file import path
     * @param string $fileType
     * @param bool   $inventory_update whether to update inventory or product
     * @param bool   $logger           true/false
     * @return bool
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function productCsvProcessor($import_path, $fileType = 'stock_sources', $inventory_update = false, $logger = false): bool
    {

        $import_file = $this->_file->getPathInfo($import_path);
        /**
         * @var \Magento\ImportExport\Model\Import $import
         */
        $import = $this->importFactory->create();
        $entity = $fileType;
        $import->setData(
            [
                'entity' => $entity,
                'behavior' => 'append',
                'validation_strategy' => 'validation-stop-on-errors',
            ]
        );

        $read_file = $this->readFactory->create($import_file['dirname']);
        $csvSource = $this->csvSourceFactory->create(
            [
                'file' => $import_file['basename'],
                'directory' => $read_file,
            ]
        );

        $validate = $import->validateSource($csvSource);
        if ($validate) {
            try {
                $result = $import->importSource();
                if ($result) {
                    $import->invalidateIndex();
                    $createdRow = $import->getCreatedItemsCount();
                    $updatedRow = $import->getUpdatedItemsCount();
                    $this->_logger->info(sprintf('Total Record Updated: %s', $updatedRow));
                }
            } catch (\Exception $exception) {
                $this->_logger->info(sprintf($exception->getMessage()));

                return false;
            }
        } else {
            $this->_logger->info(sprintf('Invalid Data'));

            return false;
        }

        return true;
    }//end productCsvProcessor()
}

Here as seen simply you can call this function productCsvProcessor with the arguments to import and update product inventory.

Hope this is helpful

Leave a Reply

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

Scroll to top