【问题标题】:How to save/download the csv content to Excel如何将 csv 内容保存/下载到 Excel
【发布时间】:2012-11-22 09:13:03
【问题描述】:

我有一个 API,它返回 csv 内容作为响应,我想以 Excel 格式下载, 我尝试了什么:

HTML:

<form id="test_form" accept-charset="utf-8" method="POST" action="http://prime.dev/index.php//data/reporting/downloadCSVFile.json"></form>

<a id="downloadcsv" class="min-button-silver">Download to Excel</a>

JS:

jQuery("#downloadcsv").click(function(e){                       jQuery('#test_form').submit();                  
});

PHP

public function downloadCSVFile()
{
    $data = $this->reporting_service->fetchCSV($request); //API request
    header("Content-Type: application/csv");        
    header("Content-Disposition: attachment; filename=test.csv");
    //header("Content-Length: ".$thesize);
    header("Pragma: no-cache");
    header("Expires: 0");
    //Will get the response from API like the below;    
    $data = 'clicks|conversions|ctr|cvr|impressions|invalid_clicks|currency.id
    4220894|127984|.1962348497109191647|.0059484688672145487|2150940063|557193|163';

    echo $data;
}

文件正在下载为 test.csv,但在记事本中打开,你们中的任何人都可以告诉我,这里出了什么问题。

提前致谢和问候

【问题讨论】:

  • Excel !== CSV 9无论分隔符是竖线还是逗号。如果您被告知使用 xls,请查看任何可以编写 实际 Excel 文件的 PHP 库 - stackoverflow.com/questions/3930975/alternative-for-php-excel
  • 如果你想改用 CSV,正确的 mime 类型是 'text/csv',而不是 'application/csv'
  • 嘿,马克贝克,感谢您的纠正。

标签: php logic export-to-csv


【解决方案1】:

如果您想下载 Excel 格式,您需要额外的软件,例如 PEAR_Spreadsheet_Excel, 因为您必须生成额外的标题和许多其他废话! 但通常,如果您创建一个正确的 CSV 文件,您也可以使用 Excel 打开它,它会显示所有列,就像在普通的 excel 文件中一样。

【讨论】:

    猜你喜欢
    • 2014-01-31
    • 2015-12-01
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 2021-12-10
    • 2014-04-08
    相关资源
    最近更新 更多