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
1 2 3 4 5 |
<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
1 2 3 |
<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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
<?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.
Any doubts about the topic or the solution can be mentioned in the Comments section below and I’d be helping you out asap. 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.
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 businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
13 Comments
Thanks for sharing your work, but how do I instantiate the class. Let me explain: how do I place the export button?
Hello Jorge,
This functionality works with the default export button in the UI grid
Thank You
Thanks for sharing your knowledge. But it didn’t work for me. I want to place a button in the products view to export. I always get an error. Try if code and nothing.
Hello Jorge,
This functionality works with default export button in UI grid
Thank You
I have add two columns in sales_order_grid.xml in ui component , column is showed in csv file but data is missing in column. I used this command
if ($component->getName() == ‘sales_order_grid’)
{
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));
}
}
Hello Nitish,
Regarding your query, it is a custom requirement and you need to put extra effort in order to fulfill your requirement.
Add a log and check the log step by step
Thank You
Hi
not Working ..
No any error..
Please tell me what is the issue?
Thank you
Hello Bhavin,
It is working from our end. Can you please check that instead of “customReportOrder_post_listing” you put the right name?
I hope it helps.
Hi,
in Magento 2.3.5 the button does not appear
Regards
Hello,
Please add the below code in UI grid XML file:
Thank you
I just want to export columns from catagory/products but can not get it to work.
Hello Train,
The default 2 does not allow to export from the product grid to generate a CSV file. This blog is for the grids having an export to CSV option in which you can add the custom column.
Thank you.
Great content , really informative and useful , appreciate you enlightening us with this!