How To

How to Export data into 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!

Click to rate this post!
[Total: 29 Average: 3.9]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

View Comments

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

1 day ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

4 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

4 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

5 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

5 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

1 week ago