In this blog, I will make sense of, how to make a CSV document in magentoMagento 2. CSV (Comma Separated Value) is one of the most well-known methods for bringing in/sending out information.
You can undoubtedly make a CSV document with PHP record compose because the arrangement of CSV record is exceptionally basic; every segment is isolated with a comma and each column is isolated with a new line. In any case, I will show how Magento gets it done or you can say the suggested way in Magento 2.
<?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 a customerlist.csv file under var/export folder. Here we have written header data in the first row and all the customcustomerers 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”.
0 comments:
Post a Comment
Thanks