-->

PHP create an excel file and return it via a funct

2019-02-19 13:51发布

问题:

I am working on yii2. I am creating an excel file via php spreadsheet. For now, I am downloading it in a browser. Now, I want to return the file without downloading it.

Code:

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

After that I want it to return the file like return $filename;

The returned file is then passed to a function named sendEmail($filename)

In this function, I have already setup email sending process via attachment.

How can I send the file without downloading it?

Note:

I have also looked at the question: PHP create Excel spreadsheet and then email it as an attachment.

回答1:

Sample code to save the file

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

Once file saved, you can send the file to mail

sendEmail('hello world.xlsx');

Once done everything you may delete the saved file

unlink('hello world.xlsx');