PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, October 4, 2022

[FIXED] How force download an .xlsx file in PHP without having it corrupted?

 October 04, 2022     excel, php, phpexcel     No comments   

Issue

None of the already existing questions have helped me. I'm trying to force download an excel file with the file type .xlsx. It works perfectly fine in a download code like this:

echo "<a href='" . $dateiname . "'>Datei herunterladen</a>";

But whenever I try to make a forced download, it doesn't work. I've tried various headers from various questions on stackoverflow, the last two being

header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $dateiname . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Pragma: no-cache');
header('Content-Length: ' . filesize($dateiname));
$objWriter->save('php://output');

and

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Transfer-Encoding: binary ");
header('Content-Disposition: attachment; filename='.basename($dateiname));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($dateiname));
$objWriter->save('php://output');

I tried both in the same file as where I create the file, but also in a separate file, but either way I always get the error:

Excel cannot open the file (filename) because the file format or file extension is not valid. Verify that the file has not been corruted and that the file extension matches the format of the file.

The file itself on my server seems perfectly fine.


Solution

I've found how I used PHPExcel to force downloading an xlsfile.

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

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

Hope it helps.



Answered By - alexey-novikov
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing