Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP创建Excel电子表格,然后将其作为附件发送电子邮件_Php_Excel_Email_Attachment - Fatal编程技术网

PHP创建Excel电子表格,然后将其作为附件发送电子邮件

PHP创建Excel电子表格,然后将其作为附件发送电子邮件,php,excel,email,attachment,Php,Excel,Email,Attachment,我正在使用以下代码: <?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; ?> 这就是当用户点击提

我正在使用以下代码:

<?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,但不能创建excel)可以做到这一点吗?

除非可以使用纯CSV,否则您需要一个库来创建实际的excel文档。CSV将在Excel中以电子表格的形式打开,但您无法执行任何高级操作,如格式化或公式

我使用图书馆PHPExcel(http://phpexcel.codeplex.com/). 它支持完整的Excel功能,包括图表和公式。它需要一点时间才能运行,而且代码非常冗长。但是,一旦你把一切都准备好了,它就像一个符咒

下面是相关代码的一个片段,它来自我的PHPExcel实现。我正在创建通过网站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 #');

编辑

根据请求,以下是实际输出我在上面创建的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");

我真的很想在不使用库的情况下执行此操作,因此我在该页面上找到了一个很好的参考,然后对其进行了调整,使用制表符分隔(\t)字符串创建了一个Excel文件

因此,您可以从数据库中获取数据以创建字符串,然后使用下面的方法发送带有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"; 
?>

--PHP混合-
内容类型:多部分/备选;boundary=“PHP alt-”
--PHP alt-
内容类型:文本/纯文本;charset=“iso-8859-1”
内容传输编码:7bit
电子邮件文本在这里
--PHP混合-
内容类型:应用程序/ms excel;name=“test.xls”
内容配置:附件

我也一直在寻找这样做的方法@Chris-PHPExcel在创建Excel文档方面看起来很棒。但是,我找不到任何关于将输出保存为变量或其他格式的内容,您可以将其作为电子邮件附件发送。你有没有想出一个办法?谢谢。当然,我编辑了答案以包含我使用的输出方法。一切正常,但问题中要求的电子邮件部分在哪里?此外,这不是创建excel文档,而是创建一个以选项卡分隔的CSV,excel可以打开它。CSV是一种通用格式,不支持Excel的任何格式功能。创建csv的方法比连接字符串更简单、更安全,例如
fputcsv(fopen('php://output数组('this','issome','csv'stuff',你知道的。)(来源:)
**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"; 
}