4

How to add Magento 2 export functionality to your module in Magento 2?

Using this side

System -> Data Transfer -> Export

Any solution??

enter image description here

Muhammad Anas
  • 1,467
  • 3
  • 12
  • 33
PradeepShinde
  • 41
  • 1
  • 2

2 Answers2

1

I crate a Admin Grid using Ui-Component.

You want all Data you have create a Custom Export Button that export your all data.

edit in your Ui-Component file where Admin Grid Show

[vendor_name] \ [module_name] \view\adminhtml\ui_component

Add this code to add Button into Admin Grid

Ui-ComponentFIleName.xml

<item name="buttons" xsi:type="array">

    <item name="import" xsi:type="array">
        <item name="name" xsi:type="string">import</item>
        <item name="label" xsi:type="string" translate="true">Import</item>
        <item name="class" xsi:type="string">secondary</item>
        <item name="url" xsi:type="string">*/*/importdata</item>
        <item name="sortOrder" xsi:type="number">20</item>
    </item>

    <item name="export" xsi:type="array">
        <item name="name" xsi:type="string">export</item>
        <item name="label" xsi:type="string" translate="true">Export</item>
        <item name="class" xsi:type="string">secondary</item>
        <item name="url" xsi:type="string">*/*/exportdata</item>
        <item name="sortOrder" xsi:type="number">30</item>
    </item>

</item>

Now create a File that Export or Import Data. File Name must be same as you define in Ui-Component file

  <item name="url" xsi:type="string">*/*/exportdata</item>

  <item name="url" xsi:type="string">*/*/importdata</item>

File path must be like this

[vendor_name] \ [module_name] \ Controller \ Adminhtml \ [Controller_name] \ Exportdata.php

Exportdata.php

<?php

namespace [vendor_name]\[module_name]\Controller\Adminhtml\[Controller_name];

use Magento\Framework\App\Filesystem\DirectoryList;


class Exportdata extends \Magento\Backend\App\Action
{
    protected $uploaderFactory;

    protected $_locationFactory; 

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Filesystem $filesystem,
        \[vendor_name]\[module_name]\Model\locatorFactory $locationFactory // This is returns Collaction of Data

    ) {
       parent::__construct($context);
       $this->_fileFactory = $fileFactory;
       $this->_locationFactory = $locationFactory;
       $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); // VAR Directory Path
       parent::__construct($context);
    }

    public function execute()
    {   
        $name = date('m-d-Y-H-i-s');
        $filepath = 'export/export-data-' .$name. '.csv'; // at Directory path Create a Folder Export and FIle
        $this->directory->create('export');

        $stream = $this->directory->openFile($filepath, 'w+');
        $stream->lock();

        //column name dispay in your CSV 

        $columns = ['Col-1-name','Col-2-name','Col-3-name','Col-4-name','Col-5-name','Col-6-name','Col-7-name','Col-8-name','Col-9-name',];

            foreach ($columns as $column) 
            {
                $header[] = $column; //storecolumn in Header array
            }

        $stream->writeCsv($header);

        $location = $this->_locationFactory->create();
        $location_collection = $location->getCollection(); // get Collection of Table data 

        foreach($location_collection as $item){

            $itemData = [];

            // column name must same as in your Database Table 

            $itemData[] = $item->getData('col-1-name');
            $itemData[] = $item->getData('col-2-name');
            $itemData[] = $item->getData('col-3-name');
            $itemData[] = $item->getData('col-4-name');
            $itemData[] = $item->getData('col-5-name');
            $itemData[] = $item->getData('col-6-name');
            $itemData[] = $item->getData('col-7-name');
            $itemData[] = $item->getData('col-8-name');
            $itemData[] = $item->getData('col-9-name');

            $stream->writeCsv($itemData);

        }

        $content = [];
        $content['type'] = 'filename'; // must keep filename
        $content['value'] = $filepath;
        $content['rm'] = '1'; //remove csv from var folder

        $csvfilename = 'locator-import-'.$name.'.csv';
        return $this->_fileFactory->create($csvfilename, $content, DirectoryList::VAR_DIR);

    }


}

Now you can Click on the Export Button and See your .csv file Downloaded below.

I Hope This Helps You.

Msquare
  • 9,063
  • 7
  • 25
  • 63
0

Try This

app/code/VendoreName/CustomDataImport/etc

db_schema.xml

<?xml version="1.0"?>

<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="custom_import"> <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" comment="Entity Id" identity="true" /> <column xsi:type="varchar" name="name" nullable="false" length="255" comment="Product Name"/> <column xsi:type="int" name="duration" padding="10" unsigned="true" nullable="false" comment="Duration"/> <constraint xsi:type="primary" referenceId="CUSTOM_IMPORT_ID_PRIMARY"> <column name="entity_id"/> </constraint> </table> </schema>

enter image description here

app/code/VendoreName/CustomDataImport/etc

import.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_ImportExport:etc/import.xsd">
    <entity name="custom_import" label="Custom Import" model="VendoreName\CustomDataImport\Model\Import\CustomImport" behaviorModel="Magento\ImportExport\Model\Source\Import\Behavior\Basic" />
</config>

app/code/VendoreName/CustomDataImport/Files/Sample

custom_import.csv

entity_id,name,duration
1,"Name 1",90
2,"Name 3",120

app/code/VendoreName/CustomDataImport/etc

di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

&lt;type name=&quot;Magento\ImportExport\Model\Import\SampleFileProvider&quot;&gt;
    &lt;arguments&gt;
        &lt;argument name=&quot;samples&quot; xsi:type=&quot;array&quot;&gt;
            &lt;item name=&quot;custom_import&quot; xsi:type=&quot;string&quot;&gt;VendoreName_CustomDataImport&lt;/item&gt;
        &lt;/argument&gt;
    &lt;/arguments&gt;
&lt;/type&gt;

</config>

app/code/VendoreName/CustomDataImport/Model/Import

CustomImport.php

<?php

namespace VendoreName\CustomDataImport\Model\Import;

use Exception; use Magento\Framework\App\ResourceConnection; use Magento\Framework\DB\Adapter\AdapterInterface; use Magento\Framework\Json\Helper\Data as JsonHelper; use Magento\ImportExport\Helper\Data as ImportHelper; use Magento\ImportExport\Model\Import; use Magento\ImportExport\Model\Import\Entity\AbstractEntity; use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface; use Magento\ImportExport\Model\ResourceModel\Helper; use Magento\ImportExport\Model\ResourceModel\Import\Data;

/**

  • Class Courses

*/ class CustomImport extends AbstractEntity { const ENTITY_CODE = 'custom_import'; const TABLE = 'custom_import'; const ENTITY_ID_COLUMN = 'entity_id';

/**
 * If we should check column names
 */
protected $needColumnCheck = true;

/**
 * Need to log in import history
 */
protected $logInHistory = true;

/**
 * Permanent entity columns.
 */
protected $_permanentAttributes = [
    'entity_id',
];

/**
 * Valid column names
 */
protected $validColumnNames = [
    'entity_id',
    'name',
    'duration',
];

/**
 * @var AdapterInterface
 */
protected $connection;

/**
 * @var ResourceConnection
 */
private $resource;

/**
 * Courses constructor.
 *
 * @param JsonHelper $jsonHelper
 * @param ImportHelper $importExportData
 * @param Data $importData
 * @param ResourceConnection $resource
 * @param Helper $resourceHelper
 * @param ProcessingErrorAggregatorInterface $errorAggregator
 */
public function __construct(
    JsonHelper $jsonHelper,
    ImportHelper $importExportData,
    Data $importData,
    ResourceConnection $resource,
    Helper $resourceHelper,
    ProcessingErrorAggregatorInterface $errorAggregator
) {
    $this-&gt;jsonHelper = $jsonHelper;
    $this-&gt;_importExportData = $importExportData;
    $this-&gt;_resourceHelper = $resourceHelper;
    $this-&gt;_dataSourceModel = $importData;
    $this-&gt;resource = $resource;
    $this-&gt;connection = $resource-&gt;getConnection(ResourceConnection::DEFAULT_CONNECTION);
    $this-&gt;errorAggregator = $errorAggregator;
    $this-&gt;initMessageTemplates();
}

/**
 * Entity type code getter.
 *
 * @return string
 */
public function getEntityTypeCode()
{
    return static::ENTITY_CODE;
}

/**
 * Get available columns
 *
 * @return array
 */
public function getValidColumnNames(): array
{
    return $this-&gt;validColumnNames;
}

/**
 * Row validation
 *
 * @param array $rowData
 * @param int $rowNum
 *
 * @return bool
 */
public function validateRow(array $rowData, $rowNum): bool
{
    $name = $rowData['name'] ?? '';
    $duration = (int) $rowData['duration'] ?? 0;

    if (!$name) {
        $this-&gt;addRowError('NameIsRequired', $rowNum);
    }

    if (!$duration) {
        $this-&gt;addRowError('DurationIsRequired', $rowNum);
    }

    if (isset($this-&gt;_validatedRows[$rowNum])) {
        return !$this-&gt;getErrorAggregator()-&gt;isRowInvalid($rowNum);
    }

    $this-&gt;_validatedRows[$rowNum] = true;

    return !$this-&gt;getErrorAggregator()-&gt;isRowInvalid($rowNum);
}

/**
 * Init Error Messages
 */
private function initMessageTemplates()
{
    $this-&gt;addMessageTemplate(
        'NameIsRequired',
        __('The name cannot be empty.')
    );
    $this-&gt;addMessageTemplate(
        'DurationIsRequired',
        __('Duration should be greater than 0.')
    );
}

/**
 * Import data
 *
 * @return bool
 *
 * @throws Exception
 */
protected function _importData(): bool
{
    switch ($this-&gt;getBehavior()) {
        case Import::BEHAVIOR_DELETE:
            $this-&gt;deleteEntity();
            break;
        case Import::BEHAVIOR_REPLACE:
            $this-&gt;saveAndReplaceEntity();
            break;
        case Import::BEHAVIOR_APPEND:
            $this-&gt;saveAndReplaceEntity();
            break;
    }

    return true;
}

/**
 * Delete entities
 *
 * @return bool
 */
private function deleteEntity(): bool
{
    $rows = [];
    while ($bunch = $this-&gt;_dataSourceModel-&gt;getNextBunch()) {
        foreach ($bunch as $rowNum =&gt; $rowData) {
            $this-&gt;validateRow($rowData, $rowNum);

            if (!$this-&gt;getErrorAggregator()-&gt;isRowInvalid($rowNum)) {
                $rowId = $rowData[static::ENTITY_ID_COLUMN];
                $rows[] = $rowId;
            }

            if ($this-&gt;getErrorAggregator()-&gt;hasToBeTerminated()) {
                $this-&gt;getErrorAggregator()-&gt;addRowToSkip($rowNum);
            }
        }
    }

    if ($rows) {
        return $this-&gt;deleteEntityFinish(array_unique($rows));
    }

    return false;
}

/**
 * Save and replace entities
 *
 * @return void
 */
private function saveAndReplaceEntity()
{
    $behavior = $this-&gt;getBehavior();
    $rows = [];
    while ($bunch = $this-&gt;_dataSourceModel-&gt;getNextBunch()) {
        $entityList = [];

        foreach ($bunch as $rowNum =&gt; $row) {
            if (!$this-&gt;validateRow($row, $rowNum)) {
                continue;
            }

            if ($this-&gt;getErrorAggregator()-&gt;hasToBeTerminated()) {
                $this-&gt;getErrorAggregator()-&gt;addRowToSkip($rowNum);

                continue;
            }

            $rowId = $row[static::ENTITY_ID_COLUMN];
            $rows[] = $rowId;
            $columnValues = [];

            foreach ($this-&gt;getAvailableColumns() as $columnKey) {
                $columnValues[$columnKey] = $row[$columnKey];
            }

            $entityList[$rowId][] = $columnValues;
            $this-&gt;countItemsCreated += (int) !isset($row[static::ENTITY_ID_COLUMN]);
            $this-&gt;countItemsUpdated += (int) isset($row[static::ENTITY_ID_COLUMN]);
        }
        if (Import::BEHAVIOR_REPLACE === $behavior) {
            if ($rows &amp;&amp; $this-&gt;deleteEntityFinish(array_unique($rows))) {
                $this-&gt;saveEntityFinish($entityList);
            }
        } elseif (Import::BEHAVIOR_APPEND === $behavior) {
            $this-&gt;saveEntityFinish($entityList);
        }
    }
}

/**
 * Save entities
 *
 * @param array $entityData
 *
 * @return bool
 */
private function saveEntityFinish(array $entityData): bool
{
    if ($entityData) {
        $tableName = $this-&gt;connection-&gt;getTableName(static::TABLE);
        $rows = [];

        foreach ($entityData as $entityRows) {
            foreach ($entityRows as $row) {
                $rows[] = $row;
            }
        }

        if ($rows) {
            $this-&gt;connection-&gt;insertOnDuplicate($tableName, $rows, $this-&gt;getAvailableColumns());

            return true;
        }

        return false;
    }
}

/**
 * Delete entities
 *
 * @param array $entityIds
 *
 * @return bool
 */
private function deleteEntityFinish(array $entityIds): bool
{
    if ($entityIds) {
        try {
            $this-&gt;countItemsDeleted += $this-&gt;connection-&gt;delete(
                $this-&gt;connection-&gt;getTableName(static::TABLE),
                $this-&gt;connection-&gt;quoteInto(static::ENTITY_ID_COLUMN . ' IN (?)', $entityIds)
            );

            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    return false;
}

/**
 * Get available columns
 *
 * @return array
 */
private function getAvailableColumns(): array
{
    return $this-&gt;validColumnNames;
}

}

Msquare
  • 9,063
  • 7
  • 25
  • 63