How to create CSV file in Magento 2

This tutorial belongs to "How to create CSV file in Magento 2". CSV stands for Comma Separated Value. Import/Export CSV is a very common way to Import/Export data in Magento 2.

if you create a CSV file, it displays data in a good format in which each column is separated with commas and row is separated with a new line. Here, I will show you how it works with an example CSV file.

 

<?php
namespace TOH\Csv\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Filesystem\DirectoryList;

class ExampleCsv 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 = 'exportCsv/customerdata.csv';
        $this->directory->create('export');
        $stream = $this->directory->openFile($filepath, 'w+');
        $stream->lock();
        $header = ['Id', 'Name', 'Email'];
        $stream->writeCsv($header);

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

            $stream->writeCsv($data);
        }
    }
}

By using the above code you can create a file named customerdata.csv which will have a list of your customer data.

This file will be saved in Var/exportCsv/ folder.

 

if you need any kind of help you can visit The Online Helper

Related Products