简体   繁体   English

从数据库创建 excel 并作为电子邮件附件发送

[英]Creating excel from database and sending as email attachment

This is my code to fetch data from database table这是我从数据库表中获取数据的代码

$sql = "select * from tbl_input_values where 1";
$result = mysql_query($sql);
$resultRows = mysql_num_rows($result);

The below is the header that I used to download file as excel format:以下是我用来将文件下载为 excel 格式的标题:

header("Content-Type: application/vnd.ms-excel");   
header("Content-Disposition: attachment; filename=test.xls");

header("Pragma: no-cache");
header("Expires: 0");

And my code to fetch the record is as follows:我获取记录的代码如下:

if($resultRows>0){
    $sep = "\t"; //tabbed character
    for ($i = 0; $i < mysql_num_fields($result); $i++) {
        echo mysql_field_name($result,$i) . "\t";
    }
    print("\n");
    while($row = mysql_fetch_row($result)){
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++){
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
        $schema_insert .= "\t"; 
        print(trim(str_replace(',', " ", $schema_insert)));
        print "\n";
    }
}

The code is working fine.代码工作正常。

So now I have to email this attachment instead of downloading it.所以现在我必须通过电子邮件发送这个附件而不是下载它。 Means when user want to create excel file the excel will be emailed to given email id.表示当用户想要创建 excel 文件时,excel 将通过电子邮件发送到给定的电子邮件 ID。

So what would be the better way to use email functionality?那么使用电子邮件功能的更好方法是什么?

Possible It can help you ....可能它可以帮助你....

if($resultRows>0){
$sep = "\t"; //tabbed character
for ($i = 0; $i < mysql_num_fields($result); $i++) {
    echo mysql_field_name($result,$i) . "\t";
}
print("\n");
while($row = mysql_fetch_row($result)){
    $schema_insert = "";
    for($j=0; $j<mysql_num_fields($result);$j++){
        if(!isset($row[$j]))
            $schema_insert .= "NULL".$sep;
        elseif ($row[$j] != "")
            $schema_insert .= "$row[$j]".$sep;
        else
            $schema_insert .= "".$sep;
    }
    $schema_insert = str_replace($sep."$", "", $schema_insert);
    $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
    $schema_insert .= "\t"; 
    print(trim(str_replace(',', " ", $schema_insert)));
    print "\n";
}

 file_put_contents('$path_to_excelfile', $schema_insert);
  }

$to = 'youraddress@example.com';

     $subject = 'Test email with attachment';

     $random_hash = md5(date('r', time()));

     $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";

     $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

     $attachment = chunk_split(base64_encode(file_get_contents('path to file')));

   mail( $to, $subject, $message, $headers ); 

REF http://webcheatsheet.com/PHP/send_email_text_html_attachment.php参考http://webcheatsheet.com/PHP/send_email_text_html_attachment.php

**Code to create excel in php:**
$dtime=date('Y-m-d H-i-s');
$dtimeFile=date('Y-m-d-H-i-s');
$headerTab ="Col1 \t Col2\t Col3\n";
$rowRecords='';
$rowRecords .=preg_replace("/\r|\n|\t/"," ",$Col1)."\t".preg_replace("/\r|\n|\t/", " ",$Col2)."\t".preg_replace("/\r|\n|\t/", " ",Col3). "\t\n";
date_default_timezone_set('America/Los_Angeles');
$filename="Your File Name-".$dtimeFile.".xls";
$path='/pathOfFile/';
$csv_handler = fopen ($path.$filename,'w');
fwrite ($csv_handler,$headerTab);
fwrite ($csv_handler,$rowRecords);
fclose ($csv_handler);

**Code to send html email with attached excel in php:**
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$headers = "From: from@gmail.com"."\r\n";
$headers.= "Bcc: bcc@gmail.com"."\r\n";
$headers.= "MIME-Version: 1.0\r\n";
$headers.= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$headers .= "This is a multi-part message in MIME format.\r\n";
$headers .= "--".$uid."\r\n";
$headers .= "Content-type:text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$headers .= $msg."\r\n\r\n";
$headers .= "--".$uid."\r\n";
$headers .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$headers .= $content."\r\n\r\n";
$headers .= "--".$uid."--"; 

$date=date("Y-m-d");
if(mail($to,"Mail heading--".$date,$msg,$headers)){
    echo "Mailed successfully";
}
else
{
    echo "Mailed couldn't be sent"; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM