{"id":1124,"date":"2020-07-17T07:49:02","date_gmt":"2020-07-17T07:49:02","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/2020\/07\/17\/include-custom-column-in-export-to-csv-in-magento-2\/"},"modified":"2025-05-22T12:10:10","modified_gmt":"2025-05-22T06:40:10","slug":"include-custom-column-in-export-to-csv-in-magento-2","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/include-custom-column-in-export-to-csv-in-magento-2\/","title":{"rendered":"How to Include Custom Column in Export To CSV in Magento 2"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Now, you might be unaware of the developer\u2019s tricks!<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, \u201cmark 1\u201d and \u201cmark 2\u201d columns are present in the database and the admin panel. Now \u201cmark 3\u201d is obtained by adding the values from the column mark 1 and mark 2 and displayed in the admin grid.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When you export to CSV from the admin panel, the mark 3 column won\u2019t be exported along with the other columns sometimes as it is not present in the database table.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The below code can be used as the solution in such cases.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Also, if you want to export CSV with custom changes made, this method to&nbsp;include custom column in export to CSV in Magento 2&nbsp;can be useful:<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Steps to Include Custom Column in Export To CSV in Magento 2:<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create&nbsp;<strong>app\/code\/Vendor\/Module\/view\/adminhtml\/ui_component\/component.xml<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;listing xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:module:Magento_Ui:etc\/ui_configuration.xsd\">\n    &lt;listingToolbar name=\"listing_top\">\n        &lt;exportButton name=\"export_button\"\/>\n    &lt;\/listingToolbar>\n&lt;\/listing><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Create&nbsp;<strong>app\/code\/Vendor\/Module\/etc\/di.xml<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;config xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"urn:magento:framework:ObjectManager\/etc\/config.xsd\">\n    &lt;preference for=\"Magento\\Ui\\Model\\Export\\ConvertToCsv\" type=\"Vendor\\Module\\Model\\Export\\ConvertToCsv\" \/>\n&lt;\/config><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Create&nbsp;<strong>app\/code\/Meetanshi\/CustomReportOrder\/Model\/Export\/ConvertToCsv.php<\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\/**\n * Copyright \u00a9 Magento, Inc. All rights reserved.\n * See COPYING.txt for license details.\n *\/\nnamespace Module\\Vendor\\Model\\Export;\nuse Magento\\Framework\\App\\Filesystem\\DirectoryList;\nuse Magento\\Framework\\Exception\\FileSystemException;\nuse Magento\\Framework\\Exception\\LocalizedException;\nuse Magento\\Framework\\Filesystem;\nuse Magento\\Framework\\Stdlib\\DateTime\\TimezoneInterface;\nuse Magento\\Ui\\Component\\MassAction\\Filter;\nuse Magento\\Ui\\Model\\Export\\MetadataProvider;\nuse Magento\\Ui\\Model\\Export\\ConvertToCsv as ConvertToCsvParent;\n\/**\n * Class ConvertToCsv\n *\/\nclass ConvertToCsv extends ConvertToCsvParent\n{\n    \/**\n     * @var DirectoryList\n     *\/\n    protected $directory;\n    \/**\n     * @var MetadataProvider\n     *\/\n    protected $metadataProvider;\n    \/**\n     * @var int|null\n     *\/\n    protected $pageSize = null;\n    \/**\n     * @var Filter\n     *\/\n    protected $filter;\n    \/**\n     * @var Product\n     *\/\n    private $productHelper;\n    \/**\n     * @var TimezoneInterface\n     *\/\n    private $timezone;\n    \/**\n     * @param Filesystem $filesystem\n     * @param Filter $filter\n     * @param MetadataProvider $metadataProvider\n     * @param int $pageSize\n     * @throws FileSystemException\n     *\/\n    public function __construct(\n        Filesystem $filesystem,\n        Filter $filter,\n        MetadataProvider $metadataProvider,\n        Product $productHelper,\n        TimezoneInterface $timezone,\n        $pageSize = 200\n    ) {\n        $this->filter = $filter;\n        $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);\n        $this->metadataProvider = $metadataProvider;\n        $this->pageSize = $pageSize;\n        $this->productHelper = $productHelper;\n        parent::__construct($filesystem, $filter, $metadataProvider, $pageSize);\n        $this->timezone = $timezone;\n    }\n    \/**\n     * Returns CSV file\n     *\n     * @return array\n     * @throws LocalizedException\n     * @throws \\Exception\n     *\/\n    public function getCsvFile()\n    {\n        $component = $this->filter->getComponent();\n        $name = md5(microtime());\n        $file = 'export\/' . $component->getName() . $name . '.csv';\n        $this->filter->prepareComponent($component);\n        $this->filter->applySelectionOnTargetProvider();\n        $dataProvider = $component->getContext()->getDataProvider();\n        $fields = $this->metadataProvider->getFields($component);\n        $options = $this->metadataProvider->getOptions();\n        $this->directory->create('export');\n        $stream = $this->directory->openFile($file, 'w+');\n        $stream->lock();\n        $stream->writeCsv($this->metadataProvider->getHeaders($component));\n        $i = 1;\n        $searchCriteria = $dataProvider->getSearchCriteria()\n            ->setCurrentPage($i)\n            ->setPageSize($this->pageSize);\n        $totalCount = (int)$dataProvider->getSearchResult()->getTotalCount();\n        while ($totalCount > 0)\n        {\n            $items = $dataProvider->getSearchResult()->getItems();\n            if ($component->getName() == 'customReportOrder_post_listing')\n            {\n                foreach ($items as $item)\n                {\n                    $this->metadataProvider->convertDate($item, $component->getName());\n                    $stream->writeCsv($this->metadataProvider->getRowData($item, $fields, $options));\n                }\n            }\n            else\n            {\n                foreach ($items as $item) {\n                    $this->metadataProvider->convertDate($item, $component->getName());\n                    $stream->writeCsv($this->metadataProvider->getRowData($item, $fields, $options));\n                }\n            }\n            $searchCriteria->setCurrentPage(++$i);\n            $totalCount = $totalCount - $this->pageSize;\n        }\n        $stream->unlock();\n        $stream->close();\n        return [\n            'type' => 'filename',\n            'value' => $file,\n            'rm' => true  \/\/ can delete file after use\n        ];\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Modify this file as per your requirement<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Execute the below command:<br><strong>php bin\/magento cache:flush<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That\u2019s it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can learn the method to&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/add-custom-column-in-order-grid-in-magento-2\/\" target=\"_blank\" rel=\"noreferrer noopener\">add a custom column in order grid in Magento 2&nbsp;<\/a>in the first place. Or you can just install&nbsp;<a href=\"https:\/\/meetanshi.com\/magento-2-custom-order-grid.html\" target=\"_blank\" rel=\"noreferrer noopener\">Magento 2 Custom Order Grid<\/a>&nbsp;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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Likewise you can also\u00a0<a href=\"https:\/\/meetanshi.com\/blog\/add-image-thumbnail-column-in-magento-2-admin-ui-grid\/\">Display image thumbnail column in Magento 2 admin UI grid<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Please share the solution with the Magento community via social media.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thank you.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Also Read: <\/strong><a href=\"https:\/\/meetanshi.com\/blog\/magento-2-export-products-into-csv\/\" target=\"_blank\" rel=\"noreferrer noopener\">Export Products into CSV in Magento 2<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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\u2019s tricks! I mean to say that there are certain columns in the admin [&hellip;]<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[34],"tags":[],"class_list":["post-1124","post","type-post","status-publish","format-standard","hentry","category-magento"],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1124","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=1124"}],"version-history":[{"count":4,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1124\/revisions"}],"predecessor-version":[{"id":14785,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1124\/revisions\/14785"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=1124"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=1124"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=1124"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}