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/vnd.ms-excel;charset=UTF-8,' + escape(data);
        var link      = document.createElement('a');
        link.href     = uri;
        link.style    = "visibility:hidden";
        link.download = table_config.toolbar.tools.export.name+'.'+file_type;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });

My export code;

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

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:
routes.php
Route::get('{id_me}/export/{table}', 'FileController@exportCsv')->where('table', 'shops|societies|axes|programs|scenarios|users|surveys');

FileController.php

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)
            ->get();

        $rows = $rows->toArray();

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

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

            });
        })->download('xls');
    }

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:

112
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...
60
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 ...
44
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...
28
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...
23
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...
17
Laravel Excel [QUESTION] XLS export not working
@edanao try cleanin the buffer before calling download function There must be some space symbol in t...
13
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: ...
246
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...
79
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...
69
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? ...
45
sheetjs Corrupt XLSX file after downloading
Ok Sorry for the monologue but I solved it: In the frontend when making the GET Request ...
44
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 ...
32
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....
27
sheetjs how to set the automatic width?
@cjlhll Please see my solution get maximum width from the json data set column width ...
20
sheetjs merge cells from Array of Arrays
You need to build up the worksheet first then add the merges to the worksheet Hi ...
20
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...
15
sheetjs format Date question
On the read side you also need to pass cellText:false: In the conversion you shouldn't set raw: raw:...
15
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 ...
15
exceljs Can't use this package on browser
I solved this by adding: declare const ExcelJS: any; and in angular.json: scripts: [ .. node_modules...
14
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...
11
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 ...
5
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 ...
3
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. ...
1344
laravel mix Laravel Mix npm run dev error
I just followed those steps and everything worked correctly Try doing a full reset: ...
556
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 (...
467
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 ...
446
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 ...
395
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...
379
laravel mix can't compile object spread operator unexpected token error
You are missing the Object rest spread transform: https://babeljs.io/docs/plugins/transform-object-r...
375
laravel mongodb Composer can't find mongodb extension
composer require jenssegers/mongodb --ignore-platform-reqs It solved my problem. ...
341
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...
298
framework [5.4] SQL error when migrating tables
In your appserviceprovider boot method try adding Best sure to import Illuminate\Support\Facades\Sch...
279
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 ...
253
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 ...
248
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...
188
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 --...
183
jwt auth Method factory does not exist.
I fixed it changing this protected function: respondWithToken replace 'expires_in' => auth()->factor...
179
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...
176
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 (...
169
jwt auth Install failed.
@Ekenzy-101 You can add --ignore-platform-reqs to force install it works well for me composer requir...
162
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...
148
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...
142
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...
140
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 ...
139
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 ...
136
lumen framework 'ReflectionException' with message 'Class path.storage does not exist'
In my case (lumen 5.3.3) got fixed by adding following lines right after $app definition in bootstra...
132
passport Key generation for Heroku deployments
@corbanb @DanTheDJ @mabumusa1 @marcospaegle run via terminal cli heroku ps:exec -a your_app_name the...
130
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...