首页 文章

在PHP中为用户创建Excel文件

提问于
浏览
0

我在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文件中写入点而不是电子邮件和日期

请帮帮我 .

1 回答

  • 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;
    

相关问题