Magento 2 custom csv export

Know Magento 2 export csv before Magento 2 custom csv export

Magento 2 core modules admin grid provide csv export from the existing grid structure. To know more about admin grid in custom module click here. In some cases, you need the custom fields of order,customer or product to export as csv file. In order to do this Magento 2 custom csv export from your custom module you need to follow the magento 2 coding standard. The below coding
snippets helps you. This code will export the order data in csv file.

Magento 2 create csv file programmatically in model

	<?php 

	use Magento\Framework\App\Filesystem\DirectoryList;
	use Magento\Framework\Filesystem;
	use Magento\Framework\Filesystem\Directory\WriteInterface;

	class Manager extends \Magento\Framework\DataObject
	{

	 public function __construct(
	 	\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
		 \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
		Filesystem $filesystem
         ){
		parent::__construct($data);
		$this->_orderCollectionFactory = $orderCollectionFactory;
       		$this->_fileFactory = $fileFactory;
        	$this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
	}

	public function orderexport(){ 
         $toDate = date('Y-m-d H:i:s', time());
         $fromDate = date('Y-m-d H:i:s', strtotime('-5 day')); 
         $headers = array('created_at','increment_id','grand_total');
         $noncancellablestatus = 'pending'; 

        // $orders = $this->_orderCollectionFactory->create()->addFieldToSelect('*')->addFieldToFilter('status','Pending');
        $orders = $this->_orderCollectionFactory->create()->addFieldToSelect('*')->addFieldToFilter('created_at', array('from'=>$fromDate, 'to'=>$toDate))->addFieldToFilter('status', $noncancellablestatus);
         $orderdetails = array();
         foreach($orders as $orderdata){
            $orderdetail['created_at'] = $orderdata->getData('increment_id');
            $orderdetail['increment_id'] = $orderdata->getData('increment_id');
            $orderdetail['grand_total'] = $orderdata->getData('grand_total');
            $orderdetails[] =  $orderdetail;
         }
       
         $exportfile = $this->getCsvdataFile($headers,$orders);
	
	}

	 public function getCsvdataFile($headers,$orders)
    	{

        $name = strtotime("now");
        $file = 'export/orderexport' . $name . '.csv';
        $this->directory->create('export');
        $stream = $this->directory->openFile($file, 'w+');
        $stream->lock();
        $stream->writeCsv($headers);
        foreach($orders as $orderdata){
            $orderdetail['created_at'] = $orderdata->getData('created_at');
            $orderdetail['increment_id'] = $orderdata->getData('increment_id');
            $orderdetail['grand_total'] = $orderdata->getData('grand_total');
            $stream->writeCsv($orderdetail);
         }
        $stream->unlock();
        $stream->close();
        return [
            'type' => 'filename',
            'value' => $file,
            'rm' => true  // can delete file after use
        ];
    }

	}	

Create a Model file or place the above the snippet code in your any model files. Add the required dependency in construct function. Then you can call the model function in controller.

Magento 2 custom csv export

Controller

	 $this->manager = $this->_objectManager->get('Alcatel\Poc\Model\Manager');
      	 $this->manager->orderexport();

Download csv file in magento 2

The above code create the csv file with required fields and download the file. The last return array was necessary for downloading the file. You can use ‘rm’ key value as false. If the value is false then the file will not be deleted, remains in temp location.

Magento 2 export fields enclosure

In the above export, I have exported only three fields ‘created_at’, ‘increment_id’, ‘grand_total’ from the order object. You can extend the export with
other fields in order object. To see all data in order object put

   
print_r($orderdata->getData()); exit; 

By doing this you can see all data of one order. Extend the export fields from the array data.

Export products magento 2

In the above mentioned same way you can do the magento 2 custom csv export of products by using the products instead of order collection factory.