2013-06-29 45 views
2

添加標題導出使用fputcsv()在csv文件中導出數據庫行。我怎麼可以添加標題首先,中心對齊然後列然後數據我的代碼運行良好,沒有標題。我知道有很多的API,但是這可能與我的代碼: - 這裏是我的代碼: -使用fputcsv php

,如: -

     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

我是唯一一個無法理解這裏被問到的東西嗎? –

+0

有幫助還是更有用? –

+0

啊,所以你試圖讓它顯示很好。使用'CSV'是不可能的,這種文件格式僅用於存儲數據。如果你想製作一個漂亮的數據表,你需要將它導出到'XSLX'中,並且沒有第三方API,這將是非常困難的。 –

回答

6

這爲我工作。

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); 
} 
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');