How to Include Custom Column in Export To CSV in Magento 2

If you are a Magento 2 store admin, you must be quite acquainted with the backend grids. You also might frequently export the data of the grid for analysis, order management, stock management, etc.

Now, you might be unaware of the developer’s tricks!

I mean to say that there are certain columns in the admin grid that are there because of some operations under the column values from the database table.

For example, “mark 1” and “mark 2” columns are present in the database and the admin panel. Now “mark 3” is obtained by adding the values from the column mark 1 and mark 2 and displayed in the admin grid.

When you export to CSV from the admin panel, the mark 3 column won’t be exported along with the other columns sometimes as it is not present in the database table.

The below code can be used as the solution in such cases.

Also, if you want to export CSV with custom changes made, this method to include custom column in export to CSV in Magento 2 can be useful:

Steps to Include Custom Column in Export To CSV in Magento 2:

Create app/code/Vendor/Module/view/adminhtml/ui_component/component.xml

<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
    <listingToolbar name="listing_top">
        <exportButton name="export_button"/>
    </listingToolbar>
</listing>

Create app/code/Vendor/Module/etc/di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Ui\Model\Export\ConvertToCsv" type="Vendor\Module\Model\Export\ConvertToCsv" />
</config>

Create app/code/Meetanshi/CustomReportOrder/Model/Export/ConvertToCsv.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Module\Vendor\Model\Export;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Ui\Component\MassAction\Filter;
use Magento\Ui\Model\Export\MetadataProvider;
use Magento\Ui\Model\Export\ConvertToCsv as ConvertToCsvParent;
/**
 * Class ConvertToCsv
 */
class ConvertToCsv extends ConvertToCsvParent
{
    /**
     * @var DirectoryList
     */
    protected $directory;
    /**
     * @var MetadataProvider
     */
    protected $metadataProvider;
    /**
     * @var int|null
     */
    protected $pageSize = null;
    /**
     * @var Filter
     */
    protected $filter;
    /**
     * @var Product
     */
    private $productHelper;
    /**
     * @var TimezoneInterface
     */
    private $timezone;
    /**
     * @param Filesystem $filesystem
     * @param Filter $filter
     * @param MetadataProvider $metadataProvider
     * @param int $pageSize
     * @throws FileSystemException
     */
    public function __construct(
        Filesystem $filesystem,
        Filter $filter,
        MetadataProvider $metadataProvider,
        Product $productHelper,
        TimezoneInterface $timezone,
        $pageSize = 200
    ) {
        $this->filter = $filter;
        $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
        $this->metadataProvider = $metadataProvider;
        $this->pageSize = $pageSize;
        $this->productHelper = $productHelper;
        parent::__construct($filesystem, $filter, $metadataProvider, $pageSize);
        $this->timezone = $timezone;
    }
    /**
     * Returns CSV file
     *
     * @return array
     * @throws LocalizedException
     * @throws \Exception
     */
    public function getCsvFile()
    {
        $component = $this->filter->getComponent();
        $name = md5(microtime());
        $file = 'export/' . $component->getName() . $name . '.csv';
        $this->filter->prepareComponent($component);
        $this->filter->applySelectionOnTargetProvider();
        $dataProvider = $component->getContext()->getDataProvider();
        $fields = $this->metadataProvider->getFields($component);
        $options = $this->metadataProvider->getOptions();
        $this->directory->create('export');
        $stream = $this->directory->openFile($file, 'w+');
        $stream->lock();
        $stream->writeCsv($this->metadataProvider->getHeaders($component));
        $i = 1;
        $searchCriteria = $dataProvider->getSearchCriteria()
            ->setCurrentPage($i)
            ->setPageSize($this->pageSize);
        $totalCount = (int)$dataProvider->getSearchResult()->getTotalCount();
        while ($totalCount > 0)
        {
            $items = $dataProvider->getSearchResult()->getItems();
            if ($component->getName() == 'customReportOrder_post_listing')
            {
                foreach ($items as $item)
                {
                    $this->metadataProvider->convertDate($item, $component->getName());
                    $stream->writeCsv($this->metadataProvider->getRowData($item, $fields, $options));
                }
            }
            else
            {
                foreach ($items as $item) {
                    $this->metadataProvider->convertDate($item, $component->getName());
                    $stream->writeCsv($this->metadataProvider->getRowData($item, $fields, $options));
                }
            }
            $searchCriteria->setCurrentPage(++$i);
            $totalCount = $totalCount - $this->pageSize;
        }
        $stream->unlock();
        $stream->close();
        return [
            'type' => 'filename',
            'value' => $file,
            'rm' => true  // can delete file after use
        ];
    }
}

Modify this file as per your requirement

Execute the below command:
php bin/magento cache:flush

That’s it.

You can learn the method to add a custom column in order grid in Magento 2 in the first place. Or you can just install Magento 2 Custom Order Grid extension that allows adding 50+ custom columns in Magento 2. Not only that, but it also offers the facility to track the order information and improve the order processing and management system in Magento 2 store.

Likewise you can also Display image thumbnail column in Magento 2 admin UI grid.

Please share the solution with the Magento community via social media.

Thank you.

Also Read: Export Products into CSV in Magento 2

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...