viest/php-ext-xlswriter

Download excel file instead of store in Folder

boedyirh opened this issue · 2 comments

Thank you for this great extension,
This extension is very fast. But How do I download generated excel file. instead of storing in folder?
Thank,
Boedy

viest commented

Hi @boedyirh

Thank you for your support, extensions do not have built-in direct download, but can be implemented through the following code:

function getTmpDir(): string
{
    if (ini_get('upload_tmp_dir') !== false) {
        if ($temp = ini_get('upload_tmp_dir')) {
            if (file_exists($temp)) {
                return realpath($temp);
            }
        }
    }

    return realpath(sys_get_temp_dir());
}

$config = [
    'path' => getTmpDir() . '/',
];

$fileName   = 'tutorial01.xlsx';
$xlsxObject = new \Vtiful\Kernel\Excel($config);

// Init File
$fileObject = $excel->fileName($fileName);

// Writing data to a file ......

// Outptu
$filePath = $fileObject->output();

// Set Header
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');

if (copy($filePath, 'php://output') === false) {
    // Throw exception
}

// Delete temporary file
@unlink($filePath);

I hope this will help you.

Thanks it works! I am able to download it.
I modify MIME Type to match XLSX (Excel 2007).
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");