Magento 2 run native product csv import programtically

All we need is an easy explanation of the problem, so here it is.

I have been searching for a way of achieving this but so far no luck. I have also looked through the core and found where it is called (vendor\magento\module-import-export\Controller\Adminhtml\Import\Start.php) but can’t work out where to define the CSV file to import.

I know I need to pass data to it like so:

Array
(
    [form_key] => 123456789xyz
    [entity] => catalog_product
    [behavior] => append
    [validation_strategy] => validation-stop-on-errors
    [allowed_error_count] => 10
    [_import_field_separator] => ,
    [_import_multiple_value_separator] => ,
    [import_images_file_dir] => 
)

Any one have any hints as to how I can run the native CSV import via code?

Thanks

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

  1. You need to inject an instance of \Magento\ImportExport\Model\Export\Adapter\CsvFactory into your constructor
  2. Using the CsvFactory, you need to create an instance of the CSV Model:

    $csvModel = $this->csvFactory->create(['destination' => 'path/to/your/file.csv']);
  3. Using the CSV Model, write out your data:

    $csvModel->writeRow(['your' => 'data']);
  4. Inject an instance of \Magento\ImportExport\Model\ImportFactory into your constructor
  5. Using the ImportFactory, you need to instantiate the Import Model:

    $importModel = $this->importModelFactory->create();
  6. Set any data you need to pass to the import model:

    $importModel->setData(['your' => 'data']);
  7. Get an instance of the CSV source model:

    $sourceModel = ImportAdapter::findAdapterFor(
    'path/to/your/file.csv',
    $this->filesystem->getDirectoryWrite(DirectoryList::ROOT),
    $importModel->getData('_import_field_separator')
    );
  8. Validate your import:

    $isValid = $importModel->validateSource($sourceModel);
  9. Handle the validation results:

    if ($importModel->getProcessedRowsCount() === 0 || !$isValid || $importModel->getErrorAggregator()->getErrorsCount()) {
    // Display or log the error
    return;
    }
  10. Run the import:

    $importModel->importSource();

There’s a lot more involved in the error handling, but this should at least get you started.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply