PHP创buildExcel电子表格,然后将其作为附件通过电子邮件发送

我使用下面的代码:

<?php $data = $_REQUEST['datatodisplay']; header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename=Data.xls"); header("Pragma: no-cache"); header("Expires: 0"); echo $data; ?> 

这是我在用户点击一个提交button时调用的。 但是我感兴趣的是发送Excel电子表格作为电子邮件附件。 所以在下面的这个文件中,我将连接到一个数据库,select结果并创build电子表格,然后将其作为附件邮寄。 这是可能的调整下面的代码(我可以做的MySQL,但只是不创build)

你需要一个库来创build一个真正的Excel文档,除非直接的CSV是可以接受的。 CSV将在Excel中以电子表格forms打开,但不能执行格式化或公式等任何高级内容。

我使用库PHPExcel(http://phpexcel.codeplex.com/)&#x3002; 它允许完整的Excelfunction,包括图表和公式。 这需要一点点,而代码是相当冗长的。 但是,一旦你把它build立起来,它就像一个魅力。

这是涉及的代码片段,这是从我的PHPExcel的实现。 我正在创build一个通过网站的API收到的贝宝付款摘要。 我只是想给你一个关于代码的数量和性质的概念。 正如你所看到的,这是所有的OO。 这只是代码的第一部分,我正在设置列标签等。 它通过循环继续进行数据放置,然后是页脚的另一部分。 它使一个非常长的文件!

 // Create new PHPExcel object $objPHPExcel = new PHPExcel(); // Set properties $objPHPExcel->getProperties()->setCreator("----- Web Server"); $objPHPExcel->getProperties()->setLastModifiedBy("-----Web Server"); $objPHPExcel->getProperties()->setTitle("Paypal payment reconciliation report"); $objPHPExcel->getProperties()->setSubject("Paypal payment reconciliation report"); $objPHPExcel->getProperties()->setDescription("Paypal payment reconciliation report"); $objPHPExcel->getProperties()->setKeywords("paypal reconcile"); $objPHPExcel->getProperties()->setCategory("Reconciliation report"); // Create a first sheet, representing sales data $objPHPExcel->setActiveSheetIndex(0); // format the heading $objPHPExcel->getActiveSheet()->setCellValue('A1', 'Paypal Reconciliation - ran on '.date('m/d/y', time())); $objPHPExcel->getActiveSheet()->mergeCells('A1:C1'); $objPHPExcel->getActiveSheet()->setCellValue('E1', 'Date Range: '.date('m/d/Y', $oldest_transaction).' to '.date('m/d/Y', $newest_transaction)); $objPHPExcel->getActiveSheet()->mergeCells('E1:J1'); $objPHPExcel->getActiveSheet()->duplicateStyleArray( array( 'font' => array( 'size' => '12', 'bold' => true ) ), 'A1:I1' ); // add column labels $objPHPExcel->getActiveSheet()->setCellValue('A2', '#'); $objPHPExcel->getActiveSheet()->setCellValue('B2', 'Date'); $objPHPExcel->getActiveSheet()->setCellValue('C2', 'Name'); $objPHPExcel->getActiveSheet()->setCellValue('D2', 'Gross'); $objPHPExcel->getActiveSheet()->setCellValue('E2', 'Fee'); $objPHPExcel->getActiveSheet()->setCellValue('F2', 'Net'); $objPHPExcel->getActiveSheet()->setCellValue('G2', 'Balance'); $objPHPExcel->getActiveSheet()->setCellValue('H2', 'Class'); $objPHPExcel->getActiveSheet()->setCellValue('I2', 'Item Title'); $objPHPExcel->getActiveSheet()->setCellValue('J2', ''); $objPHPExcel->getActiveSheet()->setCellValue('K2', '#'); $objPHPExcel->getActiveSheet()->setCellValue('L2', 'Time'); $objPHPExcel->getActiveSheet()->setCellValue('M2', 'Type'); $objPHPExcel->getActiveSheet()->setCellValue('N2', 'Status'); $objPHPExcel->getActiveSheet()->setCellValue('O2', 'Transaction ID'); $objPHPExcel->getActiveSheet()->setCellValue('P2', 'Paypal Receipt ID'); $objPHPExcel->getActiveSheet()->setCellValue('Q2', '--- #'); $objPHPExcel->getActiveSheet()->setCellValue('R2', 'Counterparty'); $objPHPExcel->getActiveSheet()->setCellValue('S2', 'Reference Txn ID'); $objPHPExcel->getActiveSheet()->setCellValue('T2', 'Inv #'); 

编辑

根据要求,这里是实际输出我上面创build的Excel文档的代码:

  include 'PHPExcel/IOFactory.php'; $file_name = date('md-Y', $oldest_transaction).'_THRU_'.date('md-Y', $newest_transaction); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('/usr/web/cache/temp/'.$file_name.'.xls'); header ("location:http://www.domain.com/cache/temp/".$file_name.".xls"); 

我真的想这样做, 而不使用库,所以我在这个页面上find一个很好的参考PHP发送带有PDF附件的电子邮件,而不创build文件? 然后调整它以使用制表符分隔(\ t)string创build一个Excel文件。

所以你可以从数据库中获取数据来创buildstring,然后使用下面的这个方法发送一个带有Excel附件的邮件

 <?php $attachment = "testdata1 \t testdata2 \t testdata3 \t \n testdata1 \t testdata2 \t testdata3 \t "; $to = 'myemail@test.com'; $subject = 'Test email with attachment'; //create a boundary string. It must be unique //so we use the MD5 algorithm to generate a random hash $random_hash = md5(date('r', time())); $headers = "From: fromEmail@test.com"; //add boundary string and mime type specification $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; //define the body of the message. ob_start(); //Turn on output buffering ?> --PHP-mixed-<?php echo $random_hash; ?> Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" --PHP-alt-<?php echo $random_hash; ?> Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Email Text here --PHP-mixed-<?php echo $random_hash; ?> Content-Type: application/ms-excel; name="test.xls" Content-Disposition: attachment <?php echo $attachment; //copy current buffer contents into $message variable and delete current output buffer $message = ob_get_clean(); //send the email $mail_sent = @mail( $to, $subject, $message, $headers ); //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" echo $mail_sent ? "Mail sent" : "Mail failed"; ?> 
 **Code to create excel in php:** $dtime=date('Ymd Hi-s'); $dtimeFile=date('YmdHi-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("Ymd"); if(mail($to,"Mail heading--".$date,$msg,$headers)){ echo "Mailed successfully"; } else { echo "Mailed couldn't be sent"; }