在PHP中为用户创建Excel文件

时间:2014-01-08 09:14:51

标签: php mysql excel

我在MySQL数据库中有数据。我正在向用户发送一个URL,以便将他们的数据作为excel文件输出。

当我们点击链接时,如何弹出一个带有MySQL记录的excel?

我已掌握所有信息以获取记录。我只是没有看到如何让PHP创建excel文件并让他们下载文件

include("con.php");

// Qry to fetch all records against date
$dateonedayback=strtotime('-1 day',strtotime(date("Y/m/d")));
$one_day=date("Y-m-d",$dateonedayback);


$qry_user_points = "SELECT u.points,u.db_add_date,u.user_email_id FROM tbl_user AS u WHERE u.points != '0' AND date(u.db_add_date)='".$one_day."' ";

$query_result= $con->db_query($qry_user_points);

header('Content-Type: application/vnd.ms-excel');   //define header info for browser
header('Content-Disposition: attachment; filename=Users-Points-Report-'.date('Ymd').'.xls');

$excel_header = array("Email","Points","Date");

for ($i = 0; $i < count($excel_header); $i++)    
{
echo $excel_header[$i]."\t";
}
print("\n");


$j=0;
while($rowValue = $con->db_fetch_array($query_result)) 
{
$points = $rowValue['points'];
$emailID = $rowValue['user_email_id'];
$addedDate = $rowValue['db_add_date'];

// create an array to insert in excel with url encoding
$final_array = array(urlencode($points),urlencode($emailID),urlencode($addedDate));

$result_count =$con->db_num_rows($query_result);

$output = '';
for($k=0; $k < $con->db_num_rows($query_result); $k++)
{
    if(!isset($final_array[$k]))
        $output .= "NULL\t";
    else
        $output .= "$final_array[$k]\t";
}
$output = preg_replace("/\r\n|\n\r|\n|\r/", ' ', $output);
print(trim($output))."\t\n";

$j++;
} // while close

当我点击链接时,它会创建excel文件,但数据不正确

它只在excel文件中写入点而不是电子邮件&amp;日期

请帮助我。

1 个答案:

答案 0 :(得分:0)

例如,您可以使用PEAR Spreadsheet lib http://pear.php.net/package/Spreadsheet_Excel_Writer

此lib创建excel文件,而不应使用设置右标题

将内容发送给用户

通过邮件:

        $sid = md5(uniqid(time()));
        $header = "From: Automatic report system<admin@example.com>\nReply-to: admin@example.com\nMIME-Version: 1.0\nContent-Type: multipart/mixed; boundary=\"$sid\"\n\n";
        $header .= "This is multi-part message in MIME format.\n--$sid\n";
        $header .= "Content-type: text/plain; charset=utf-8\n\n";
        $length = filesize($filePath);
        $header .= "--$sid\nContent-type: application/octet-stream; name=\"$fileTitle.xls\"\n";
        $header .= "Content-Transfer-Encoding: base64\n";
        $header .= "Content-Disposition: attachment; filename=\"$fileTitle.xls\"\nContent-Length: $length\n\n";
        $header .= chunk_split(base64_encode(file_get_contents($filePath))) . "\n\n\n\n";
        mail('recepient@example.com', 'New report', null, $header);

通过浏览器:

        $length = filesize($filePath);
        header("Content-type: application/octet-stream");
        header("Content-Disposition: attachment; filename=\"$fileTitle.xls\"");
        header("Content-Length: $length");
        readfile($filePath);
        exit;