PHP创建一个excel文件并通过函数返回它

时间:2018-05-28 06:09:15

标签: php yii2 attachment yii2-advanced-app phpspreadsheet

我正在研究yii2。我正在通过php spreadsheet创建一个excel文件。目前,我正在浏览器中下载它。现在,我想在不下载的情况下返回文件。

代码

// Created 2 worksheet in one excel file successfully 

$filename = 'Meter Breakdown List '.date('d-m-y').'.xlsx'; //save our workbook as this file name
    // Redirect output to a client’s web browser (Xlsx)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="'.$filename.'"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');

    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');

    $writer->save('php://output');

之后,我希望它返回return $filename;

之类的文件

然后将返回的文件传递给名为sendEmail($filename)

的函数

在此功能中,我已经通过附件设置了电子邮件发送过程。

如何在不下载文件的情况下发送文件?

注意:

我也看过这个问题:PHP create Excel spreadsheet and then email it as an attachment

1 个答案:

答案 0 :(得分:2)

示例code以保存文件

<?php

require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World !');

$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');

保存文件后,您可以将文件发送到邮件

sendEmail('hello world.xlsx');

完成所有操作后,您可以删除已保存的文件

unlink('hello world.xlsx');