我正在尝试使用csv文件中的fputcsv()导出数据库行。我如何首先添加标题,中心对齐然后列,然后数据我的代码工作良好,没有标题。我知道有很多api,但这可能在我的代码中: - 这是我的代码: -
如: -
Enquiery Report
id name class func
1 rk ba call()
2 bk bd that()
function exportdata_to_excel($details) {
// filename for download
$filename = date("Y-m-d").".csv";
header('Content-Type: text/csv');
header("Content-Disposition: attachment; filename=\"$filename\"");
$out = fopen("php://output", 'w');
$flag = false;
//$result = $orderDetails;
while($row = mysql_fetch_assoc($details)) {
$arr =array('Enquiry id'=>$row['id'],'Date'=>$row['created_on'],'Name'=>$row['name'], 'Email'=>$row['email'], 'Telephone'=>$row['telephone'], 'Customer Request'=>$row['customer_request'], 'Special Request'=>$row['special_request']);
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($arr), ',', '"');
$flag = true;
}
fputcsv($out, array_values($arr), ',', '"');
}
fclose($out);
exit();
}
答案 0 :(得分:9)
这对我有用。
function downloadCSV($data)
{
$filename = date("Y-m-d").".csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);
header("Content-Transfer-Encoding: UTF-8");
$f = fopen('php://output', 'a');
fputcsv($f, array_keys($data[0]));
foreach ($data as $row)
{
fputcsv($f, $row);
}
fclose($f);
}
答案 1 :(得分:2)
打开文件后尝试此操作,您要写入例如我想在下面的路径写一个文件:
$fp = fopen('csvfiles/myfile.csv','w')
您必须单独输入标题,因此为此创建一个标题数组,如:
$csv_fields=array();
$csv_fields[] = 'Enquiry id';
$csv_fields[] = 'Date';
$csv_fields[] = 'Name';
$csv_fields[] = 'Email';
$csv_fields[] = 'Telephone';
$csv_fields[] = 'Customer Request';
$csv_fields[] = 'Special Request';
制作标题后,将这些标题添加到文件中。
fputcsv($fp, $csv_fields);
while($row = mysql_fetch_assoc($details)) {
fputcsv($fp,$row);
}
fclose($fp);
还在顶部添加以下标题,以便可以轻松查看文件:
header("content-type: application/force-download");
header('Content-Type: application/csv');
header('Pragma: no-cache');