当前位置: 技术文章>> 如何在Magento 2中的每个订单上自动生成CSV文件?

文章标题:如何在Magento 2中的每个订单上自动生成CSV文件?
  • 文章分类: Magento
  • 12697 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


在Magento 2中为每个订单自动生成CSV文件的步骤:

步骤1:转到下面的文件路径

app\code\Vendor\Extension\etc\events.xml

然后,按如下方式添加代码

<?xml version='1.0'?>
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='urn:magento:framework/Event/etc/events.xsd'>
   <event name='sales_order_place_after'>
        <observer
                name='sales_order_place_after'
                instance='Vendor\Extension\Observer\GenerateCSV'
        />
    </event>
</config>

步骤2:下一步移至以下文件路径

app\code\Vendor\Extension\Observer\GenerateCSV.php

然后添加以下代码片段

<?php
 
namespace Vendor\Extension\Observer;
 
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
 
class GenerateCSV implements ObserverInterface
{
     protected $_objectManager;
     private $logger;
     private $productFactory;
 
     public function __construct(
          \Magento\Framework\ObjectManagerInterface $objectManager,
          \Psr\Log\LoggerInterface $logger,
          \Magento\Catalog\Model\ProductFactory $productFactory,
          \Magento\Framework\Filesystem $filesystem)
     {
          $this->_objectManager = $objectManager;
          $this->logger = $logger;
          $this->productFactory = $productFactory;
           $this->directory = $filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
     }
 
     public function execute(\Magento\Framework\Event\Observer $observer)
     {
          $order = $observer->getEvent()->getOrder();
          $order_id = $order->getIncrementId();
          $customerfirstname = $order->getCustomerFirstname();
          $customerlastname = $order->getCustomerLastname();
   
          $filepath = 'export/'.$order_id.'.csv';
          $this->directory->create('export');
          $stream = $this->directory->openFile($filepath, 'w+');
          $stream->lock();
 
          $header = ['Order Id', 'Customer FirstName', 'Customer LastName'];
          $stream->writeCsv($header);
       
          $data[] = $order_id;
          $data[] = $customerfirstname;
          $data[] = $customerlastname;
          $stream->writeCsv($data);
     }
}

步骤3:之后运行以下命令

php bin/magento setup:di:compile
php bin/magento cache:flush

您可以看到为Magento 2商店中下的每个订单生成如下所示的CSV。

结论:

通过这种方式,您可以在Magento 2中的每个订单上自动生成CSV文件。 在Magento 2中生成订单报告,以轻松管理发货和交付。


推荐文章