Site icon MageComp Blog

How to Export data into CSV file Programmatically in Magento 2

How to Export CSV file Programmatically in Magento 2

Whichever industry you work in, you will almost certainly have come across a story about how “data” is changing the face of our world. In general, data is merely a collection of information. But when it comes to Ecommerce, there are several types of data like business data, transactional data, customer data, sales data, product data, and the list goes on that plays an important role. And this data helps a lot to analyze progress, taxation, future planning or to restore business from accidental damage.

Magento allows the store owner to export store data in comma-separated values (CSV) file which uses a delimited text file that uses a comma to separate values. By default, you can export various Magento store data like order data, customer data and sales data but what if you want to export customized data?

We are back again with an Exciting blog to export data in CSV file Programmatically In Magento 2. Here we have exported customer details with some required data for your consideration. To use this code put below code into controller file.

app\code\vendor\extension\Controller\Index\Export\Classname.php

namespace Vendor\Extension\Controller\Export;

class Classname extends \Magento\Framework\App\Action\Action
{
	protected $fileFactory;
	protected $csvProcessor;
	protected $directoryList;

	public function __construct(
        \Magento\Framework\App\Action\Context $context,
    	\Magento\Customer\Model\Session $customerSession,
    	\Magento\Framework\App\Response\Http\FileFactory $fileFactory,
    	\Magento\Framework\File\Csv $csvProcessor,
        \Magento\Framework\App\Filesystem\DirectoryList $directoryList
	)
	{
    	$this->fileFactory = $fileFactory;
    	$this->csvProcessor = $csvProcessor;
    	$this->directoryList = $directoryList;
    	parent::__construct($context, $customerSession);
	}

	public function execute()
	{
    	$fileName = 'csv_filename.csv';
    	$filePath = $this->directoryList->getPath(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR)
        	. "/" . $fileName;

    	$customer = $this->_customerSession->getCustomer();
    	$personalData = $this->getPresonalData($customer);

    	$this->csvProcessor
    	    ->setDelimiter(';')
        	->setEnclosure('"')
        	->saveData(
            	$filePath,
            	$personalData
        	);

    	return $this->fileFactory->create(
        	$fileName,
        	[
            	'type' => "filename",
            	'value' => $fileName,
            	'rm' => true,
        	],
            \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR,
        	'application/octet-stream'
    	);
	}

	protected function getPresonalData( \Magento\Customer\Model\Customer $customer )
	{
    	$result = [];
    	$customerData = $customer->getData();
    	$result[] = [
        	'address_id',
        	'firstname',
        	'middlename',
        	'lastname',
 	       'email',
        	'company',
        	'street',
        	'telephone',
        	'fax',
    	];

    	$result[] = [
        	null,
        	$customerData['firstname'],
        	$customerData['middlename'],
        	$customerData['lastname'],
        	$customerData['email'],
        	null,
        	null,
        	null,
        	null,
    	];


    	$addressId = 1;
    	foreach ($customer->getAddresses() as $address) {
        	$result[] = [
            	$addressId,
            	$address['firstname'],
            	$address['middlename'],
            	$address['lastname'],
            	null,
            	$address['company'],
            	$address['street'],
            	$address['telephone'],
            	$address['fax'],
        	];
        	$addressId++;
    	}

    	return $result;
	}
}

You can use inside your custom extension or for your requirements of exporting data.
Lastly, hit that falling stars if the code worked for you and don’t forget to comment down below if you are looking for any help regarding this code.
Happy Coding!

Exit mobile version