Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

How to Create CSV files in Magento

If you want to create downloadable csv of you ordered item's you can use following script.

$orders = Mage::getModel("sales/order")->getCollection();
// prepare CSV header
$csv = '';
$_columns = array(
     "Order Id",
     "Product Name",
     "Sku",
     "Price"
);
$data = array();
// prepare CSV header...
foreach ($_columns as $column) {
       $data[] = '"'.$column.'"';
}
$csv .= implode(',', $data)."\n";
foreach ($orders as $order) {
         $items = $order->getAllItems();
         foreach ($items as $item) {
               $loadProduct = Mage::getModel('catalog/product')->load($item->getProductId());
               //prepare csv contents
                $data = array();
                $data[] = $order->getId();
                $data[] = $loadProduct['name'];
                $data[] = $loadProduct['sku'];
                $data[] = $loadProduct['price'];

                $csv .= implode(',', $data)."\n";
               //now $csv varaible has csv data as string
    }
}
     
$this->_redirect('*/*/');
$this->_prepareDownloadResponse('file.csv', $csv, 'text/csv');

Please support us, Like us on Facebook.

  1. Where we have to put this code. Please suggest. I am new in Magento.

    ReplyDelete
    Replies
    1. You can put in your root of magento installation or in your header for temporarily.

      Delete

 

Copyright @ 2017 HKBlog.