How to Create a CSV file in Magento 2

In this article, 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.
You can easily create csv file with php class file write because the format of csv file is very simple; each column are separated with comma and each row are separated with new line.
However, we will show how magento does it.

For your information, We will create a csv file with customers list with columns as Customer Id, Name and Email.

namespace Mageclues\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
	protected $_customerFactory;
	protected $_directory;
    public function __construct(
        Context $context,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Customer\Model\CustomerFactory $customerFactory
    ) {
        $this->_customerFactory = $customerFactory;
        $this->_directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
    public function execute()
        $filepath = 'export/customer_entity_list.csv';
        $stream = $this->_directory->openFile($filepath, 'w+');

        $header = ['CustomerID', 'Name', 'Email'];

        $collection = $this->_customerFactory->create()->getCollection();
        foreach ($collection as $customer) {
            $customerData = [];
            $customerData[] = $customer->getId();
            $customerData[] = $customer->getName();
            $customerData[] = $customer->getEmail();

This will create customer_entity_list.csv file under var/export folder.

Let me know in comment if there is any confusion. I hope this article helpful for you.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *