PhpSpreadsheet -下载文件而不是保存

mwg9r5ms  于 2023-01-29  发布在  PHP
关注(0)|答案(7)|浏览(335)

我需要生成一个excel文件(xls),并在生成后触发下载。我在documentation中找到了这个例子。

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

它展示了如何创建一个excel文件并将其保存在服务器上。我如何将结果提供给客户端并“强迫”他下载它?我需要以某种方式获得$writer的数据。
我目前正在解决它没有PhpSpreadsheet:

// Excel Export 
    $filename = 'export_'.date('d-m-y').'.xls';
    $filename = $validator->removeWhitespace($filename);

    header('Content-type: application/ms-excel');
    header('Content-Disposition: attachment; filename='.$filename);
    exit($response["output"]);  // <-- contains excel file content

但是它不能与我的分隔符(分号)一起工作。分号没有得到解释,所有内容都被写进了一列。

如果我将其导出为.csv,那么它可以工作。但我需要它作为.xls或.xlsx

gr8qqesn

gr8qqesn1#

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

class DownloadExcel
{
    public static function createExcel(array $data, array $headers = [],
                                       $fileName = 'data.xlsx')
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        for ($i = 0, $l = sizeof($headers); $i < $l; $i++) {
            $sheet->setCellValueByColumnAndRow($i + 1, 1, $headers[$i]);
        }

        for ($i = 0, $l = sizeof($data); $i < $l; $i++) { // row $i
            $j = 0;
            foreach ($data[$i] as $k => $v) { // column $j
                $sheet->setCellValueByColumnAndRow($j + 1, ($i + 1 + 1), $v);
                $j++;
            }
        }

        $writer = new Xlsx($spreadsheet);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="'. urlencode($fileName).'"');
        $writer->save('php://output');
    }

}

这就是我用PhpSpreadsheet创建电子表格并直接输出到php://output以供下载所用的代码。

w6mmgewl

w6mmgewl2#

我遇到了同样的问题,并在这里找到了解决方案:https://github.com/PHPOffice/PhpSpreadsheet/issues/217
我用$writer->save('php://output');结束了我的方法,然后又用exit()结束了我的方法

hxzsmxv2

hxzsmxv23#

我的答案:PHP:

$writer = new Xlsx($spreadsheet);
ob_start();
$writer->save('php://output');
$ret['data'] = base64_encode(ob_get_contents());
ob_end_clean();

联森:

var linkSource = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,'+ response.data ;
var downloadLink = document.createElement("a");
var fileName = 'clients.' + format;

downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
r7s23pms

r7s23pms4#

我用一个变通方法解决了这个问题,我把文件暂时保存在服务器上,然后把内容加载到一个变量中,并把它作为下载文件,然后从服务器上删除这个文件。

    • 解决方法:**
$date = date('d-m-y-'.substr((string)microtime(), 1, 8));
$date = str_replace(".", "", $date);
$filename = "export_".$date.".xlsx";

try {
    $writer = new Xlsx($response["spreadsheet"]);
    $writer->save($filename);
    $content = file_get_contents($filename);
} catch(Exception $e) {
    exit($e->getMessage());
}

header("Content-Disposition: attachment; filename=".$filename);

unlink($filename);
exit($content);
lg40wkob

lg40wkob5#

调用ob_end_clean()函数;就在$writer-〉保存(“php://output”)之前。

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

ibps3vxo6#

这对我很有效:

$excel = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$sheet = $excel->getActiveSheet();
$sheet->setTitle('This is a test', true);

ob_end_clean();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="filename_' . time() . '.xlsx"');
header('Cache-Control: max-age=0');

$xlsxWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($excel, 'Xlsx');
$xlsxWriter = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($excel);
exit($xlsxWriter->save('php://output'));
bzzcjhmw

bzzcjhmw7#

如果你的文件下载失败,最好检查一下文件输出的顶部是否有多余的空格。如果你的PHP文件有空白的白线,而HTML没有问题,你的phpspreadsheet文件会有问题。花了很多时间试图修复这些问题,但问题是空格!

相关问题