2

I want to create an excel format file for download in Magento 2

<item name="buttons" xsi:type="array">
        <item name="add" xsi:type="array">
            <item name="name" xsi:type="string">add</item>
            <item name="label" xsi:type="string" translate="true">Add a new Guest</item>
            <item name="class" xsi:type="string">primary</item>
            <item name="url" xsi:type="string">*/*/newAction</item>
        </item>

        <item name="xml" xsi:type="array">
            <item name="name" xsi:type="string">xml</item>
            <item name="label" xsi:type="string" translate="true">Excel Download</item>

            <item name="url" xsi:type="string">*/export/gridToXls</item>
        </item>
    </item>

enter image description here

I have the skeleton for my GridToXls action here:

class GridToXls extends Action
 {

  public function execute(){
    //do
   }
 }

How do I create and prepare the excel file for download in a Magento 2 custom module?

1
  • Please correct your question. You've asked for excel download, but you've accepted an answer that downloads as CSV. May be that's the requirement for you, but it will mislead others, like I reached here. Excel and CSV are not same.
    – Duke
    Nov 29, 2020 at 11:48

1 Answer 1

5

In Magento 2 Native, One php class \Magento\Framework\App\Response\Http\FileFactory is used for create csv and download CSV by magento way. create() function in FileFactory.php is used for create CSV file. There are many another way to download CSV file using Core PHP script but its not best way to use within Magento Coding standard. You can write CSV and download a CSV file using just simple below code snippet in your controller file, namespace {your vendor}\CSV\Controller\Adminhtml\Index;

use Magento\Framework\App\Filesystem\DirectoryList;

class Export extends \Magento\Backend\App\Action
{
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Filesystem $filesystem
    ) {
        $this->orderRepository = $orderRepository;
        $this->_fileFactory = $fileFactory;
        $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
        parent::__construct($context);
    }

    public function execute()
    {
        $name = date('m_d_Y_H_i_s');
        $filepath = 'export/custom' . $name . '.csv';
        $this->directory->create('export');
        /* Open file */
        $stream = $this->directory->openFile($filepath, 'w+');
        $stream->lock();
        $columns = $this->getColumnHeader();
        foreach ($columns as $column) {
            $header[] = $column;
        }
        /* Write Header */
        $stream->writeCsv($header);

        $products[] = array(1,'Test 1','test 1',100);
        $products[] = array(2,'Test 2','test 2',299);

        foreach ($products as $item) {
            $itemData = [];
            $itemData[] = $item[0];
            $itemData[] = $item[1];
            $itemData[] = $item[2];
            $itemData[] = $item[3];
            $stream->writeCsv($itemData);
        }

        $content = [];
        $content['type'] = 'filename'; // must keep filename
        $content['value'] = $filepath;
        $content['rm'] = '1'; //remove csv from var folder

        $csvfilename = 'Product.csv';
        return $this->_fileFactory->create($csvfilename, $content, DirectoryList::VAR_DIR);

    }

    /* Header Columns */
    public function getColumnHeader() {
        $headers = ['Id','Product name','SKU','Price'];
        return $headers;
    }
}

When you run controller action you can download CSV file using just Magento straight forward way. Using the above way you can download CSV file using Magento 2 Way.you can customize on your requirement

14
  • Thanks, Shafeel Sha. It's working for me Sep 9, 2019 at 7:02
  • @NiteshKumarSingh your welcome , Happy coding :) Sep 9, 2019 at 7:03
  • Fatal error: Uncaught TypeError: Argument 1 passed to namespace\models\Controller\Adminhtml\Export\GridToXls::__construct() must be an instance of Magento\Backend\App\Action\Context, instance of Magento\Framework\ObjectManager\ObjectManager given, called in /tyresnmore/20190705151145/lib/internal/Magento/Framework/ObjectManager/Factory/AbstractFactory.php on line 93 Sep 9, 2019 at 8:39
  • run on server getting error Sep 9, 2019 at 8:40
  • please run baisc commands > Sep 9, 2019 at 8:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.