we will explain you, How to create a CSV file in magento 2. CSV (Comma Separated Value) file is one of the most easy way to import/export magento entity data.Create Export CSV File Programmatically in Magento 2 by FileFactory Class.
However, I will show how magento does it or you can say the recommended way in Magento 2.
So for example I will create a csv file with customers list with columns as CustomerId, Customer Name and Customer Email.
\Magento\Framework\App\Response\Http\FileFactory used to create CSV and download CSV by Magento way. create() function in FileFactory.php is used for create CSV file.
There are many other ways to download CSV files using Core PHP script but its not the best way to use within the Magento Coding standard.
<?php namespace Dolphin\Csv\Controller\Index; use Magento\Framework\App\Action\Action; use Magento\Framework\App\Action\Context; use Magento\Framework\App\Filesystem\DirectoryList; class CreateCsv extends Action { public function __construct( Context $context, \Magento\Framework\Filesystem $filesystem, \Magento\Customer\Model\CustomerFactory $customerFactory ) { $this->customerFactory = $customerFactory; $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR); parent::__construct($context); } public function execute() { $filepath = 'export/allcustomer.csv'; $this->directory->create('export'); $stream = $this->directory->openFile($filepath, 'w+'); $stream->lock(); $header = ['CustomerId', 'Customer Name', 'Customer Email']; $stream->writeCsv($header); $collection = $this->customerFactory->create()->getCollection(); foreach ($collection as $customer) { $customerData = []; $customerData[] = $customer->getId(); $customerData[] = $customer->getName(); $customerData[] = $customer->getEmail(); $stream->writeCsv($customerData); } } }
This will create allcustomer.csv file under var/export folder.
If you want to know how can you download this csv file programmatically then please check out our blog “How to Download Csv File in Magento 2”.
I Hope, This instruction will be helpful for you.
If you have any difficulties regarding this blog, do consider them posting in the Comments section below!
I’m here to help.
Thank you!