PHP—SQL下载为EXCEL文件

<?php
/*
 * Created on 2011-7-13
 * long.tang
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
?>
<?php require_once('conn.php');
	   require_once('checklogin.php');
		require_once('function.php');


//用php将mysql中的数据导出到.csv文件

function saveFileInCsvFormat($fileName, $data){
    // 判断文件是否存在,不存在就创建文件,存在就返回false

    if (!file_exists($fileName)){

        $file = fopen($fileName,'x');

    }else {

        return false;

    }
    // 将数据写入 csv 文件内容

    foreach ($data as $val){

        fputcsv($file, $val);

    }
    // 保存文件

    @fclose($file);

    return true;

}
function downFile($sFilePath)
{
   if(file_exists($sFilePath)){
	   echo "<script language=javascript>window.location='$sFilePath';</script>";
   }
   else
   {
       echo("文件不存在!");
   }
}


if(isset(GET["tactic_id"])){
	$tactic_i_maillist = "tactic_".GET["code"]."_click";
	$sql_data = "select t.mclick_time,l.tactic_link_id,l.mlink_address from mail_click t,mail_link l where t.mlink_id=l.tactic_link_id and t.tactic_id=l.tactic_id and t.data_id=".GET["code"]." and t.tactic_id=".GET["tactic_id"];
	$fileName = 'down/'.$tactic_i_maillist."_".date('YmdHis').'.csv';
}


//echo "$sql_data";
$result_data = @db_query($sql_data, $conn_com, $data_type_com, $error_com);

$fields = @db_num_fields($result_data, $data_type_com);
$j = 0;
$k = 0;
for ($i=0; $i < $fields; $i++) {

	$field_name = @db_field_name($result_data,$i,$data_type_com);
	$data[$j][$i] = $field_name;
}
while ($row_data = @db_fetch_assoc($result_data, $data_type_com)){
		$j++;
		$data[$j] = $row_data;
}

saveFileInCsvFormat($fileName,$data);
//echo $fileName;




//文件下载函数
if(isset($fileName)){
   downFile($fileName);
}
else
{
   echo("请输入文件路径!");
}

?>


你可能感兴趣的:(Excel)