Wednesday, April 12, 2017

CSV - Magento 2


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
/**
*
* Copyright © 2016 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace [Your_NameSpace]\[Your_Module]\Controller\Download;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;
class Download extends \Magento\Framework\App\Action\Action
{
/**
* @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
*/
protected $_productCollectionFactory;
   
public function __construct(
    Context $context,
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
) {
    $this->_productCollectionFactory = $productCollectionFactory;
    parent::__construct($context);
}
public function execute()
{
    $notificationId = $this->getRequest()->getParam('notification_id');
    $heading = [
        __('Id'),
        __('SKU'),
        __('Name')
    ];
    $outputFile = "ListProducts". date('Ymd_His').".csv";
    $handle = fopen($outputFile, 'w');
    fputcsv($handle, $heading);
    foreach ($productCollection as $product) {
        $row = [
            $product->getId(),
            $product->getSku(),
            $product->getName()           
        ];
        fputcsv($handle, $row);
    }
    $this->downloadCsv($outputFile);
}
public function downloadCsv($file)
{
    if (file_exists($file)) {
        //set appropriate headers
        header('Content-Description: File Transfer');
        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();flush();
        readfile($file);
    }
}
}

No comments:

Post a Comment