【发布时间】:2014-08-03 17:23:06
【问题描述】:
我正在生成一个 csv 文档,csv 文件生成正确但文件没有下载。
我尝试过的代码:
这是我将数据从数据库表导出到csv文件的功能
$file = export_excel_csv()
这是我尝试过但失败的下载脚本
if (file_exists('payment_reports/'.$file)) {
//set appropriate headers
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
//read the file from disk and output the content.
readfile($file);
exit;
}
将数据从 db 放入 excel 的功能:
function export_excel_csv()
{
$file_name = strtotime("now").".csv";
$file_namepath = "payment_reports/".$file_name; // file name will be created here (originally file is created, as we are just fixing the name of the csv file)
$fp = fopen($file_namepath,"w"); // opening the file to write the date, here in this step file will be created
$sql_query = "MYQUERY";
$result_getData = mysql_query($sql_query);
$row_data = mysql_fetch_assoc($result_getData); // as we are dealing with files, better to use mysql_fetch_assoc, we can also use mysql_fetch_array but better to use mysql_fetch_assoc
$comma = ""; // initializing the variables
$seperator = "";
// this foreach to get the column name from the database and writes data to csv file
foreach($row_data as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""',$name); // $name will be having table column names.
$comma = ",";
}
$seperator .= "\n";
fputs($fp,$seperator); //puts the columns names in the csv file
// ends writing headings into csv file
mysql_data_seek($result_getData, 0); // leaves the first line in the csv file
while($row_data = mysql_fetch_assoc($result_getData)) //fetching the table data to write into csv file
{
$comma = "";
$seperator = "";
foreach($row_data as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""',$value); // $value will be having table data.
$comma = ",";
}
echo 'usd : '.$row_data['usd'].'<br>';
$total_usd += $row_data['usd'];
$seperator .= "\n";
fputs($fp,$seperator);
}
$seperator_usd .= ",";
$seperator_usd .= ",";
$seperator_usd .= "Total USD,";
$seperator_usd .= $total_usd;
fputs($fp,$seperator_usd);
return $file_name;
}
【问题讨论】:
-
您没有像在
file_exists()中那样将绝对/正确路径传递给basename()和filesize()函数 -
内容类型:文本/csv,而不是“应用程序/csv”
-
抱歉没找到你。你能告诉我具体哪里需要修改
-
@user4035 我尝试过使用 text/csv 但无法正常工作
-
@prassu 如果您的 csv 生成正确,那么为什么不将页面重定向到该 csv 并让浏览器自行下载。