如何使用连续列导出到csv

时间:2013-07-31 07:14:26

标签: php mysql excel csv

我想将mysql数据导出到包含concat 4列的csv文件,但它无法正常工作,任何人都可以尽快帮助我 我想连接Add1,Add2,Add3,City,Pincode这些列它将显示在csv文件的单列中

Thnx提前

我的PHP代码如下

<?php

require_once("config.php");



//Enter the headings of the excel columns
$contents="SR NO,DATE,AGENT NAME,PROCESS,DONAR NAME,ADDRESS,CONTACT NO,NEAREST STATION,SUBURBANS,PICKUP TIME,CONFIRMATION STATUS,PICKUP AMOUNT,FIELD EXECUTIVE\n";

//Mysql query to get records from datanbase
//You can customize the query to filter from particular date and month etc...Which will depends your database structure.
$Sr_no=$_GET['Sr_no'];
$dt=date('Y-m-d');

$user_query = mysql_query("SELECT Sr_no,Entry_Date,Agent_Name,Process_Name,Donar_Name,CONCAT( IFNULL( Add1,  '' ) , ' ', IFNULL( Add2,  '' ) , ' ', IFNULL( Add3,  '' ),' ',IFNULL( City,  '' ),'', IFNULL( Pincode,  '' ) ) AS Full_Address,Mobile_no,Nearest_station,Suburbans,Pickup_time,Confirmation_Status,Pickup_Amount,Field_Executive FROM leads where Entry_Date='$dt'");

//While loop to fetch the records
while($row = mysql_fetch_array($user_query))
{

$contents.=$row['Sr_no'].",";
$contents.=$row['Entry_Date'].",";
$contents.=$row['Agent_Name'].",";
$contents.=$row['Process_Name'].",";
$contents.=$row['Donar_Name'].",";
$contents.=addslashes($row['Full_Address']).",";
//$contents.=$row[{['Add1']}{$row['Add2']}{$row['Add3']}].",";
$contents.=$row['Mobile_no'].",";
$contents.=$row['Nearest_station'].",";
$contents.=$row['Suburbans'].",";
$contents.=$row['Pickup_time'].",";
$contents.=$row['Confirmation_Status'].",";
$contents.=$row['Pickup_Amount'].",";
$contents.=$row['Field_Executive']."\n";

}



// remove html and php tags etc.
$contents = strip_tags($contents); 

//header to make force download the file
header("Content-Disposition: attachment; filename=Leads For".date('d-m-Y').".csv");
print $contents;



?>

3 个答案:

答案 0 :(得分:0)

改变这个:

$contents.=$row[{['Add1']}{$row['Add2']}{$row['Add3']}].",";

到此:

$contents.="{$row['Add1']}{$row['Add2']}{$row['Add3']},";

答案 1 :(得分:0)

像这样改变

$contents.=$row['Add1'].$row['Add2'].$row['Add3'].",";

答案 2 :(得分:0)

将您的查询更改为

SELECT Sr_no,Entry_Date,Agent_Name,Process_Name,Donar_Name,
       CONCAT_WS(" ", Add1,Add2,Add3,City,PinCode) AS Full_Address,
       Mobile_no,Nearest_station,Suburbans,Pickup_time,Confirmation_Status,
       Pickup_Amount,Field_Executive FROM leads where Entry_Date='$dt'");

然后使用fputcsv是个好主意,而不是自己为输出构建一个字符串

header("Content-Disposition: attachment; filename=Leads For".date('d-m-Y').".csv");
$fp = fopen("php://output", "w");
fputcsv($fp, array("SR NO","DATE","AGENT NAME","PROCESS","DONAR NAME","ADDRESS","CONTACT NO","NEAREST STATION","SUBURBANS","PICKUP TIME","CONFIRMATION STATUS","PICKUP AMOUNT","FIELD EXECUTIVE"));
while($row = mysql_fetch_array($user_query))
{
   // strip tags out of the field
   $row = array_map("strip_tags", "row");
   fputcsv($fp, $row);
}
fclose($fp);