2016-04-12 178 views
1

我需要將結果從MySQL查詢導出到codeigniter中的csv文件中。將數據導出爲CSV在CodeIgniter中

這是模型:

public function export_csv() 
{ 

     $this->load->dbutil(); 
    $this->load->helper('file'); 
    $this->load->helper('download'); 
    $delimiter = ","; 
    $newline = "\r\n"; 
    $file_name = 'BVN_REPORTS'.date("Y-m-d h-i-s").'.csv'; 
    $query = 'SELECT account_name as "Account Name", 
    api_account_name as "Verified Name", 
    account_num "Account Number", 
    bvn "Bank Verification Number (BVN)", bank_name as "BANK NAME" 
    from ew_employees where bvn is not null 
    ORDER BY bank_name '; 
    $result = $this->db->query($query); 
    $data = $this->dbutil->csv_from_result($result, $delimiter, $newline); 
    if(force_download($filename, $data)){ 
    echo 'Done'; 
    } 
    else {echo 'Not Done';} 
    } 

這是控制器:

public function get_csv() 
{ 
    $this->load->model('employees_model'); 
    $this->employees_model->export_csv(); 
} 

的結果總是「未完成」 ......我怎樣才能強制查詢的CSV下載結果。謝謝

+0

確定文件被加載? –

+0

該文件應該動態創建並填充查詢結果 – ewom2468

+0

檢查手動文件是否創建 –

回答

1

根據問題標題讓我回答這個問題。一般來說,它可能有助於其他訪問這裏。 當我將數據導出到csv時,我通常會這樣做。

function data_to_csv($data, $headers = TRUE, $filename= "") 
{ 
    if (! is_array($data)) 
    { 
     show_error('invalid Data provided'); 
    } 

    $array = array(); 

    if ($headers) 
    { 
     $array[] = array_keys($data[0]); 
    } 
    foreach ($data as $row) 
    { 
     $line = array(); 
     foreach ($row as $item) 
     { 
      $line[] = $item; 
     } 
     $array[] = $line; 
    } 
     header("Content-type: application/csv"); 
     header("Content-Disposition: attachment; filename=\"$filename".".csv\""); 
     header("Pragma: no-cache"); 
     header("Expires: 0"); 

     $handle = fopen('php://output', 'w'); 

     foreach ($array as $array) { 
      fputcsv($handle, $array); 
     } 
      fclose($handle); 
     exit; 
} 
0

控制器

$result = $this->registration_model->exportToCsv(); 
    header("Content-type: application/csv"); 
    header("Content-Disposition: attachment; filename=\"application".".csv\""); 
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    $handle = fopen('php://output', 'w'); 
    fputcsv($handle, array('Sr No.', 'Apply for', 'Name', 'mobile', 'email_id', 'work_experinece', 'pan', 'refrence', 'pro_img1', 'pro_img2', 'created_at')); 
        $i = 1; 
        foreach ($result as $data) { 
         fputcsv($handle, array($i, $data["apply_for"], $data["full_name"], $data["mobile"], $data["email_id"], $data["work_experinece"], $data["pan"], $data["refrence"], $data["pro_img1"], $data["pro_img2"], $data["created_at"])); 
         $i++; 
        } 
         fclose($handle); 
        exit; 

型號

$this->db->select("apply_for,full_name,mobile,address,email_id,work_experinece,pan,refrence,pro_img1,pro_img2,created_at"); 
$this->db->order_by("app_id", "DESC"); 
$this->db->from("tablename"); 
$query = $this->db->get(); 
return $query->result_array();