Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5489

How to Create a CSV file in Magento 2

$
0
0

In this blog, I will explain, how to create a csv file in magento 2. CSV (Comma Separated Value) is one of the most common way to import/export data. You can easily create csv file with php 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, 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 Id, Name and Email.

<?php
namespace Webkul\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/customerlist.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);
        }
    }
}

This will create customerlist.csv file under var/export folder. Here we have written header data in the first row and all the customers data are written through the foreach loop.

If you want to know how can you download this csv file programmatically then please check out our blog “Programmatically Download File in Magento 2”.

Please comment if you face any issue or if there is any confusion. Thanks for checking out the blog.


Viewing all articles
Browse latest Browse all 5489

Trending Articles