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 ways 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 is separated with a comma, and each row is separated with a 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 a customer 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 the customerlist.csv file under the 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 you download this CSV file programmatically, then please check out our blog “Programmatically Download File in Magento 2”.
Please comment if you face any issues or if there is any confusion. Thanks for checking out the blog.
If you require technical support, feel free to email us at [email protected]
Additionally, explore a wide array of solutions to boost your store’s capabilities by visiting our Adobe Commerce modules section and Adobe Commerce marketplace addons.
Or looking to improve your store’s speed and overall performance? Check out our Magento 2 Speed & Optimization services.
Get expert support and build customized solutions by hiring skilled Adobe Commerce developers for your project.
Be the first to comment.