SolvedLaravel Excel [QUESTION] XLS export not working

I've read through the older issues about the blank space prior to the <?php. But I've searched and could not find any in the controller, model, and route in relation to the export call.

I'm using the latest Laravel, & Laravel-Excel Package.
My Link code;

      $.post(export_url, export_data, function(data){
        var uri       = 'data:application/;charset=UTF-8,' + escape(data);
        var link      = document.createElement('a');
        link.href     = uri;    = "visibility:hidden"; ='.'+file_type;

My export code;

return Excel::create($name, function($excel) use($records) {
            $excel->sheet('Sheet 1', function($sheet) use($records) {

When I try to open the file. It is corrupt. This same code works fine with CSV

24 Answers

✔️Accepted Answer

@edanao, try cleanin the buffer before calling download function. There must be some space symbol in the code which triggers the error.

if (ob_get_level() > 0) { ob_end_clean(); }

Other Answers:

Hi, I've encountered the same bug.
I've read all the issues about removing the blank spaces before "<?php" and I removed all last empty lines.
That does not change the fact that xls/xlsx export doesnt not work as it should.
Here is my code:
Route::get('{id_me}/export/{table}', 'FileController@exportCsv')->where('table', 'shops|societies|axes|programs|scenarios|users|surveys');


public function     exportCsv(Request $request)
        $table      = $request->route('table');
        $model      = $this->loadModel($table);
        $society_id = $request->route('id_me');

        $rows = $model
            ->where('society_id', $society_id)

        $rows = $rows->toArray();

        Excel::create($table, function($excel) use ($rows, $table)
            $excel->setTitle("Exportation des " . $table);

            $excel->sheet('shops', function($sheet) use ($rows)


This code works like a charm with csv extension not xls or xlsx.
By not working i mean that it render unreadable data.

Here is my setup:
Laravel 5.1
"maatwebsite/excel": "~2.1.0"

I'm pretty sure i've removed all trailling spaces before <?php and at the end of files, I've checked for like 2 hours more or less even in files that is probably not parsed in this case.

No offense, but this should be highly considered as a bug to fixe.
Even if removing what's have to be removed to solve the problem is an "ok" solution for some, it is too much of a project maintainability issue for what can be a minor usage of this library (in my case).

Thanks for your work and attention, I really like to use Laravel-excel even if I'm still struggling to get some of the implemented feature to work as planned

@edanao, try cleanin the buffer before calling download function. There must be some space symbol in the code which triggers the error.

if (ob_get_level() > 0) { ob_end_clean(); }

Thanks it worked For Me

Related Issues:

Laravel Excel Error Opening file with Excel. Possible data corrupted or bad file extension.
Hi everyone I spend my day to understand this unworkable download function PHPSpreadSheet seems to u...
Laravel Excel [BUG] import date format issue
I started working on a PR but quickly realized that it was going to be complicated to implement ...
Laravel Excel How to: save csv/xls files using ajax only
I needed to return an xlsx from ajax so I tweaked again a little and this is what I end up with: PHP...
Laravel Excel Start row (2) is beyond highest row (1)
i have same error ! but after remove sheet 2 3 solved !! for this situation you need define sheet in...
Laravel Excel How to insert clickable hyperlink in excel?
when use v3.* u can like this to set hyper link Helpful solution but you can do it more understandab...
Laravel Excel [QUESTION] XLS export not working
@edanao try cleanin the buffer before calling download function There must be some space symbol in t...
Laravel Excel [BUG] Error import: object beginTransaction
Maybe you guys are having the same issue I did at #2384 Maybe my solution would work for you try a: ...
sheetjs How to simply export a Worksheet to xlsx?
There are two issues: each object is mapped to a row so if you want a row with name John and city Se...
sheetjs Doesn't work with browserify or webpack.
I was able to get it building by adding the following to my webpack config: EDIT: please raise a new...
exceljs Add a rows before the columns headers
By that example do this @rihabbs That's about it Hi how can i add a rows before the column header? ...
sheetjs Corrupt XLSX file after downloading
Ok Sorry for the monologue but I solved it: In the frontend when making the GET Request ...
sheetjs Change header´s title when using json_to_sheet
There's no json_to_xlsx function you probably mean json_to_sheet That being said the easiest way is ...
spout Get validation error message after opening created .xlsx file
This is not a library issue Use exit; immediately after $writer->close(); as with downloading files....
sheetjs how to set the automatic width?
@cjlhll Please see my solution get maximum width from the json data set column width ...
sheetjs merge cells from Array of Arrays
You need to build up the worksheet first then add the merges to the worksheet Hi ...
exceljs "Zone.js has detected that ZoneAwarePromise (window|global).Promise has been overwritten
fixed mine by importing it before 'core-js' and 'zone.js' in the pollyfills.ts file pollyfills.ts fi...
sheetjs format Date question
On the read side you also need to pass cellText:false: In the conversion you shouldn't set raw: raw:...
exceljs Cannot resolve module 'fs' on client side
@Ahmad19860 So .writeFile relies on node.js libraries in order to function So we can't actually use ...
exceljs Can't use this package on browser
I solved this by adding: declare const ExcelJS: any; and in angular.json: scripts: [ .. node_modules...
sheetjs Date conversion loses 1 day
My date in excel is 2019-03-04 and finally i got 2019-03-03T15:59:17.000Z when XLSX.utils.sheet_to_j...
sheetjs Get the header column from excel
@kalai7890 If you just want to pull the header row the easiest way is to just walk the cells in the ...
node csvtojson fs.exists is not a function
It seems you are trying to use the lib in Browser and fs module only exists in nodejs For browser ...
visidata AttributeError: '_curses.curses window' object has no attribute 'get_wch'
@qrkourier I just followed pyenv/pyenv#240 (comment): with a few changes Now it works. ...
laravel mix Laravel Mix npm run dev error
I just followed those steps and everything worked correctly Try doing a full reset: ...
laravel mix Cannot find module cross-env
cross-env must have updated its paths it has cross-env/dist/bin not cross-env/bin/ in package.json (...
passport "storage/oauth-private.key" does not exist or is not readable.
I think you didn't correctly install passport Please run this command: Hi ...
laravel mix Error: Cannot find module '@babel/compat-data/corejs3-shipped-proposals'
I fixed this issue with: sudo npm update --depth 5 @babel/preset-env After then ...
laravel dompdf (1/1) ErrorException Non-static method Barryvdh\DomPDF\PDF::loadView() should not be called statically
This happens because you are namespacing the wrong PDF class You are namespacing Barryvdh\DomPDF\PDF...
laravel mix can't compile object spread operator unexpected token error
You are missing the Object rest spread transform:
laravel mongodb Composer can't find mongodb extension
composer require jenssegers/mongodb --ignore-platform-reqs It solved my problem. ...
framework query that worked in Laravel 5.2 gives me error in Laravel 5.3
Ok Laravel can also enable this mode when querying This query works in 5.2: my gallery table looks l...
framework [5.4] SQL error when migrating tables
In your appserviceprovider boot method try adding Best sure to import Illuminate\Support\Facades\Sch...
valet In Brew.php line 187: Unable to determine linked PHP.
I've had the same problem tonight I try methods: composer global update install php 72 brew upgrade ...
jwt auth Argument 3 passed to Lcobucci\JWT\Signer\Hmac::doVerify() must be an instance of Lcobucci\JWT\Signer\Key, null given
Run php artisan jwt:secret that works for me Subject of the issue Describe your issue here ...
laravel mix npm run dev error
Please try: Laravel Mix Version: 1.2.2 Node Version: v8.1.4 NPM Version: 5.3.0 OS: macOS 10.12.5 Des...
laravel activitylog >PHP7.2: Declaration of Orchestra\Testbench\TestCase::setUp() must be compatible with PHPUnit\Framework\TestCase::setUp()
@AndresMatta in TestCase.php file add :void public function setUp(): void phpunit --coverage-text --...
jwt auth Method factory does not exist.
I fixed it changing this protected function: respondWithToken replace 'expires_in' => auth()->factor...
telescope ReflectionException: Class env does not exist
setting TELESCOPE_ENABLED=false in my .env.dusk.local or .env solved the issue Not sure this is real...
passport Obtain access token and refresh token without a http request
In my case i need login user with no password i do it: create a trait App/Traits/PassportToken.php (...
jwt auth Install failed.
@Ekenzy-101 You can add --ignore-platform-reqs to force install it works well for me composer requir...
framework Laravel not compatiable with php 7.2
I solved the problem putting the next code at the beginning of the controller: If you don't know wha...
dusk Exception: It is unsafe to run Dusk in production.
I just wanted to share what was my issue when getting this exception When installing to production s...
laravel mix Vue.js Async Components
@ruchern It is specific to webpack (tooling) after all it is babel who will transform the code and w...
horizon Timeout for long running task
I already found a solution to my problem Hi I have a task that will take a few minutes to complete ...
ddev In WSL2 ddev start fails at docker-credential-desktop.exe, "error listing credentials"
I had to set credsStore: in my ~/.docker/config.json .. it was previously set to credentials.exe ...
lumen framework 'ReflectionException' with message 'Class does not exist'
In my case (lumen 5.3.3) got fixed by adding following lines right after $app definition in bootstra...
passport Key generation for Heroku deployments
@corbanb @DanTheDJ @mabumusa1 @marcospaegle run via terminal cli heroku ps:exec -a your_app_name the...
valet cURL error 6: Could not resolve: site.test (Domain name not found)
It's interesting that it's only curl that's giving trouble and only with Guzzle I'm not convinced th...