Joomla将报告导出或下载到CSV

时间:2014-01-16 14:49:43

标签: excel csv joomla header

我运行此代码时,我的库存部分中有以下代码,它保存了一个excel文件,但结果显示整个html文件不是我的数据。

<?php

$csv = NULL;
$arr = array("product_name","product_sku","product_in_stock","virtuemart_product_id","product_price_display","product_instock_value");
$csv = "Product Name, Product SKU, In Stock, Booked ordered products, Cost Price, Stock Value \n";
$c=0;
while(list($key,$value)=each($arr)){
$c++;
$cc=1;
foreach ($this->inventorylist as $key => $product){
$cc++;
$csv .= join(',',array($product->product_name.",".$product->product_sku.",".$product->product_in_stock.",".$product->virtuemart_product_id.",".$product->product_price_display.",".$product->product_instock_value))." \n";

}

}

JResponse::clearHeaders();
JResponse::setHeader('Content-Type', 'application/vnd.ms-excel', true);
JResponse::setHeader('Content-Disposition', 'csv; filename=inventory_report.csv; size='.strlen($csv), true);
JResponse::sendHeaders();

任何帮助将不胜感激。

由于

Khalique

1 个答案:

答案 0 :(得分:1)

这是蛮力解决方案,只是为了让你前进:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

// Echo the csv content.
echo "foo,bar\n1,2";

// Close the application gracefully.
JFactory::getApplication()->close();

不使用视图的方式稍微更清晰,但URL中包含&format=raw

$app = JFactory::getApplication();
$doc = JFactory::getDocument();

$doc->setMimeEncoding('application/vnd.ms-excel');

$app->setHeader(
    'Content-disposition',
    'attachment; filename="inventory_report.csv"',
    true
);

echo "foo,bar\n1,2";

但最好的方法是使用基于raw文档类型的下载视图。您可以在com_banners中找到相关示例:

您可能还会从此讨论中获得一些额外的见解https://groups.google.com/forum/#!topic/joomla-dev-general/dRa_39AGDBY