How to create a excel file and need to save in root directory?
-
01-10-2020 - |
Question
I tried to create to a excel file and need to save that created file some places.
$filename = 'request_quote.xlsx';
$exportData[0]['product_id'] = 123;
$exportData[0]['product_name'] = 123;
$exportData[0]['vendor_name'] = 123;
$data[0]=array($this->__("Product ID"),$this->__("Product Name"),$this->__("Vendors"));
$i=1;
foreach($exportData as $key=>$value){
$data[$i]=array($value['product_id'],$value['product_name'],$value['vendor_name']);
$i++;
}
$xmlObj = new Varien_Convert_Parser_Xml_Excel();
$xmlObj->setVar('single_sheet', $filename);
$xmlObj->setData($data);
$xmlObj->unparse();
$content = $xmlObj->getData();
$this->_prepareDownloadResponse($filename,$content);
When i use above code, its forced me to download the excel file.
now my question is how to save that file in folder or root directory?
Note: not a csv file.
Solution
prepareDownloadResponse()
is used to declare headers and content type in response for file download from browser.
So you need to change the code
from
$this->_prepareDownloadResponse($filename,$content);
to
$io = new Varien_Io_File();
$io->setAllowCreateFolders(true);
$io->open(array('path' => Mage::getBaseDir()));
if ($io->fileExists('filename.Extension') && !$io->isWriteable('filename.Extension')) {
// file does not exist or is not readable
return;
}
$io->streamOpen('filename.Extension');
$io->streamWrite($content);
$io->streamClose();
to write the file to filename.Extension
in the root directory (Mage::getBaseDir()
)
OTHER TIPS
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('category_ids');
$fp = fopen('exports.csv', 'w+');
$csvHeader = array('id',"sku", "category_ids");
fputcsv( $fp, $csvHeader,",");
foreach ($products as $product){
$sku = $product->getSku();
$ID = $product->getId();
$categoryIds = implode('|', $product->getCategoryIds());//change the category separator if needed
fputcsv($fp, array($ID, $sku, $categoryIds), ",");
}
fclose($fp);
it will generate excel file in root directory
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange