2016-09-27 77 views
0
<?php 
require_once("db_connect.php"); 
$arr = $_GET['arr']; 

$selected_header = implode(', ', (array)$arr); 

$sql = "SELECT $selected_header FROM release_ ORDER BY id DESC"; 

header('Content-Type: application/vnd.ms-excel'); 
header('Content-Disposition: attachment; filename=CNC-'.date('Ymd').'.xls'); 
header('Pragma: no-cache'); 
header('Expires: 0'); 

$output = ''; 
$output .= '<table><tr>'; 

$header_arr = explode(',', $arr); 
$len = count($header_arr); 


for($a=0; $a<$len; $a++){ 
    $output .= "<th style='width: 100px; text-align: center;'>" . $header_arr[$a] . "</th>"; 
} 
$output .= '</tr>'; 

$res = mysqli_query($conn, $sql); 

/*====this ruins everything=====*/ 
while($row = $res->fetch_assoc()){ 
    $output = '<tr align="center">'; 
    for($a=0; $a<$len; $a++){ 
     $output .= "<td>" . $header_arr[$a] . "</td>"; 
    } 

    echo "</tr>\t\n"; 
} 
/*===============================*/ 

$output .= '</table>'; 
echo $output; 

?>Excel导入

我能够获取和显示Excel文件的标题,但内容不会显示在所有。我得到了显示整行的行标记。我如何能够将数据库中的数据显示为excel文件。请帮忙。

+0

它看起来像你的代码实际上是建立一个HTML表格。如果你想要一个Excel文件,你应该使用一个库,比如PHPExcel。 –

+0

@MDB是您的查询正确运行,特别是查询中的这个release_是什么。是你的表名 – rahul

回答

0

我已经在我的项目(CakePHP的),你可以使用这样自己的方式完成的: -

public function ExportToExcel(){ 
    $users_id = $this->Session->read('selected_user_id'); 
    $this->loadModel('User'); 
    $conditions= array('User.usertype !='=>1); 
    if(!empty($users_id)){ 
     $ids=explode(",",$users_id); 
     $conditions = array(
      'User.id'=>$ids 
      ); 
    } 
    $users = $this->User->find('all',array(
     'conditions'=>$conditions, 
     'order'=>array('User.id Desc') 
     ) 
    ); 
    ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large 
    $filename = "Users" . date("Y.m.d") . ".xls"; 
    header('Content-type: application/ms-excel'); 
    header('Content-Disposition: attachment; filename="' . $filename . '"'); 
    $i = 1; 
    $row=""; 
    $row_header="S.No."."\t"."Name "."\t"."Email"."\t"."Mobile"."\t"."Address"."\t"."Status"."\n"; 
    if(!empty($users)){ 
     foreach($users as $user){ 
      if($user['User']['status']==1){ 
       $status = "Active"; 
      } 
      else{ 
       $status = "Inactive"; 
      } 

      $row .= $i++."\t".$user['User']['firstname'].' '.$user['User']['lastname'] 
      ."\t".$user['User']['email'] 
      ."\t".$user['User']['phone_number'] 
      ."\t".$user['User']['address'] 
      ."\t".$status 
      ."\n"; 
     } 
    } 
    $this->Session->delete('selected_user_id'); 
    echo($row_header); 
    echo($row); 
    die; 
}