2011-02-14 94 views
5

我用下面的代碼:PHP創建Excel電子表格,然後通過電子郵件以附件形式

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

?> 

這就是我所說的,當用戶點擊提交按鈕。但我感興趣的是將Excel電子表格作爲電子郵件附件發送。因此,在下面的這個文件中,我將連接到數據庫,選擇結果並創建電子表格,然後將其作爲附件郵寄。這有可能通過調整下面的代碼(我可以做的MySQL,但只是不擅長創作)

回答

8

你需要一個庫創建一個實際的Excel文檔,除非直CSV是可以接受的。 CSV將在Excel中作爲電子表格打開,但不能執行任何格式化或公式等高級內容。

我使用圖書館PHPExcel(http://phpexcel.codeplex.com/)。它允許完整的Excel功能,包括圖表和公式。它需要一點時間才能完成,代碼非常冗長。但是,一旦你完成所有設置,它就像一個魅力。

這裏涉及的代碼片段,這是從我實現PHPExcel的。我創建了通過網站的API接收的Paypal付款摘要。我只是爲了讓你瞭解所涉及代碼的數量和性質。正如你所看到的,這都是OO。這只是代碼的第一部分,我設置了列標籤等。它像這樣通過循環來放置數據,然後是頁腳的另一部分。它使一個V E R Y長文件!

// 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 #'); 

編輯

按要求,這裏是代碼實際輸出Excel文檔我上面創建:

include 'PHPExcel/IOFactory.php'; 
    $file_name = date('m-d-Y', $oldest_transaction).'_THRU_'.date('m-d-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"); 
+0

我一直在尋找一種方式來做到這一點以及。 @Chris - PHPExcel看起來非常適合創建Excel文檔。但是,我找不到任何有關將輸出保存爲變量或其他格式的信息,然後您可以將它們作爲附件發送到電子郵件。你有沒有碰到過這樣做的方法?謝謝。 – 2011-03-14 22:21:39

+0

當然,我編輯的答案包括我使用的輸出方法。 – 2011-03-15 18:49:19

1

我真的很想做這沒有使用庫,所以我在這個頁面上找到了一個很好的參考PHP Send email with PDF attachment without creating the file?,然後調整它來創建一個Ex cel文件使用製表符分隔(\ t)字符串。

所以,你可以從數據庫中獲取數據,以建立一個字符串,然後使用下面這個方法來發送電子郵件與Excel附件

<?php 
$attachment = "testdata1 \t testdata2 \t testdata3 \t \n testdata1 \t testdata2 \t testdata3 \t "; 

$to = '[email protected]'; 
$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: [email protected]"; 
//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"; 
?> 
1
**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: [email protected]"."\r\n"; 
$headers.= "Bcc: [email protected]"."\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"; 
}