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.

<?php
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);
        parent::__construct($context);
    }
 
    public function execute()
    {
        $filepath = 'export/customer_entity_list.csv';
        $this->_directory->create('export');
        $stream = $this->_directory->openFile($filepath, 'w+');
        $stream->lock();

        $header = ['CustomerID', 'Name', '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 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 *