Laravel-excel: Como: salvar arquivos csv / xls usando apenas ajax

Criado em 14 jul. 2016  ·  12Comentários  ·  Fonte: Maatwebsite/Laravel-Excel

Oi, pessoal,

Eu vi que alguns de nós estão tentando servir arquivo a partir de uma solicitação ajax. Depois de alguma pesquisa, não encontrei nenhuma solução clara para fazer isso. Ajustando alguns deles, exportei com sucesso os dados csv e xls de uma solicitação Ajax. A questão é que a manipulação é diferente se o tipo de arquivo for xls, por causa da codificação, então há alguns ajustes.

Os dados vêm de uma consulta típica do Eloquent, convertida em Array:

PHP

if(!empty(Input::get('exportType'))) { //i use a custom get parameter here
            $dd = Excel::create('testFileName', function($excel) use ($data) {
                $excel->sheet('testSheetName', function($sheet) use ($data) {
                    $sheet->fromArray($data->get()->toArray());
                });
                $excel->setTitle($filename);
                $excel->setLastModifiedBy(Carbon::now()->toDayDateTimeString()); //updated has Carbon::now() only now throw exception on vendor/phpoffice/phpexcel/Classes/PHPExcel/Writer/Excel5.php l847 strlen()
            });

            //tweak for serving XLS file from ajax (or go trough download() Excel method for csv files)
            if(Input::get('exportType') == 'xls') {
                $dd = $dd->string();
                $response =  array(
                    'filename' => 'testFileName', //as we serve a custom response, HTTP header for filename is not setted by Excel. From the JS, you need to retrieve this value if type is XLS to set filename
                    'file' => "data:application/vnd.ms-excel;base64,".base64_encode($dd)
                );
                return response()->success($response); //do a json encode
            } else {
                //direct use of Excel download method for non-xls files - xls files need special JS treatment
                $dd->download(Input::get('exportType')); //not XLS, so CSV (didnt tried xlsx, pdf is blank but not sure it's related to this)
            }
            die; //prevent malformed binary data stream, not sure if needed
        }

JS

$.ajax({
      cache: false,
      url: url, //GET route 
      responseType: 'ArrayBuffer', //not sure if needed
      data:  exportParam, //exportType parameter here
      success: function (data, textStatus, request) {

//you could need to decode json here, my app do it automaticly, use a try catch cause csv are not jsoned

        //already json decoded? custom return from controller so format is xls
        if(jQuery.isPlainObject(data)) {
          data = data.data; //because my return data have a 'data' parameter with the content
        }

        //V1 - http://stackoverflow.com/questions/35378081/laravel-excel-using-with-ajax-is-not-working-properly
        //+V3 - http://stackoverflow.com/questions/27701981/phpexcel-download-using-ajax-call
        var filename = "";
        var disposition = request.getResponseHeader('Content-Disposition');
        if (disposition && disposition.indexOf('attachment') !== -1) {
          var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
          var matches = filenameRegex.exec(disposition);
          if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
        }
        if(!jQuery.isPlainObject(data)) { //is CSV - we use blob
           var type = request.getResponseHeader('Content-Type');
           var blob = new Blob([data], { type: type ,endings:'native'});
           var URL = window.URL || window.webkitURL;
           var downloadUrl = URL.createObjectURL(blob);
        }
        var a = document.createElement("a");
        a.href = jQuery.isPlainObject(data) ? data.file : downloadUrl; 
        a.download = jQuery.isPlainObject(data) ? data.filename : filename;
        document.body.appendChild(a);
        a.click();
        a.remove();
      },
      error: function (ajaxContext) {
        toastr.error('Export error: '+ajaxContext.responseText);
      }
    });

ps: isso não é um problema

Comentários muito úteis

Eu precisava devolver um xlsx do ajax, então ajustei um pouco novamente e acabei com isso:

PHP
$ data é uma consulta do Eloquent convertida em Array.

$myFile= Excel::create("filename", function($excel) use($data) {
   $excel->setTitle('title');
   $excel->sheet('sheet 1', function($sheet) use($data) {
     $sheet->fromArray($data, null, 'A1', true, true);
   });
});

$myFile = $myFile->string('xlsx'); //change xlsx for the format you want, default is xls
$response =  array(
   'name' => "filename", //no extention needed
   'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".base64_encode($myFile) //mime type of used format
);
return response()->json($response);

js

$.ajax({
      cache: false,
      url: url, //GET route 
      data:  params, //your parameters data here
      success: function (response, textStatus, request) {
        var a = document.createElement("a");
        a.href = response.file; 
        a.download = response.name;
        document.body.appendChild(a);
        a.click();
        a.remove();
      },
      error: function (ajaxContext) {
        toastr.error('Export error: '+ajaxContext.responseText);
      }
    });

Todos 12 comentários

Muito obrigado, funciona bem para CSV, mas não para xls,

Eu precisava devolver um xlsx do ajax, então ajustei um pouco novamente e acabei com isso:

PHP
$ data é uma consulta do Eloquent convertida em Array.

$myFile= Excel::create("filename", function($excel) use($data) {
   $excel->setTitle('title');
   $excel->sheet('sheet 1', function($sheet) use($data) {
     $sheet->fromArray($data, null, 'A1', true, true);
   });
});

$myFile = $myFile->string('xlsx'); //change xlsx for the format you want, default is xls
$response =  array(
   'name' => "filename", //no extention needed
   'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".base64_encode($myFile) //mime type of used format
);
return response()->json($response);

js

$.ajax({
      cache: false,
      url: url, //GET route 
      data:  params, //your parameters data here
      success: function (response, textStatus, request) {
        var a = document.createElement("a");
        a.href = response.file; 
        a.download = response.name;
        document.body.appendChild(a);
        a.click();
        a.remove();
      },
      error: function (ajaxContext) {
        toastr.error('Export error: '+ajaxContext.responseText);
      }
    });

obrigado!!

Estou recebendo o erro "Classe 'Excel' não encontrada". Você poderia me ajudar?

@randomhoodie alguma fonte de como você descobriu essa solução?

@eldyvoon como eu disse, "ajustei" a resposta original, tire o que eu não precisava, torne-o compacto e duckduckgo (mecanismo de pesquisa) para o tipo mime da extensão ms office xlsx, não tinha certeza se era vai funcionar até eu tentar, mas eu tentei antes de postar, e como funcionou eu postei, caso alguém ache útil.

Descobri que nenhum javascript nem ajax são necessários. Tenho uma página da web com links para baixar vários arquivos csv / xls / xlsx diferentes e não quero que a página seja atualizada de forma alguma. Tudo que fiz foi conectar um link a uma ação que retornou o seguinte ...

public function getSpreadsheet () {
$ items = Item :: all ();
Excel :: criar ('itens', função ($ excel) usar ($ itens) {
$ excel-> sheet ('ExportFile', função ($ sheet) use ($ items) {
$ sheet-> fromArray ($ items);
});
}) -> exportar ('xls');
}

Wonderfull !!!!

Obrigado @randomhoodie!

Para o pacote 3.x, eu atualizaria seu PHP com algo assim, de acordo com o guia de atualização :

        $myFile = Excel::raw(new YOUR_Export_Class, \Maatwebsite\Excel\Excel::XLSX);

        $response =  array(
           'name' => "filename", //no extention needed
           'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".base64_encode($myFile) //mime type of used format
        );

        return response()->json($response);

Obrigado @kynetiv , uso a versão 3.x, mas precisava colocar uma extensão como: filename.xlsx

Se você ainda estiver tendo esse problema em 2020. Observe que a versão 3.x do Laravel excel mudou, então aqui está a solução

  1. Envie seus dados através do Ajax para o seu controlador que interage com o objeto Laravel Excel
  2. Deixe o objeto excel do Laravel enviar seus dados para uma visualização em lâmina
  3. Armazene a visualização da lâmina no servidor
  4. use js para baixar o arquivo no servidor.
    Portanto, a ideia é exportar uma visualização blade como excel e armazená-la em um local de disco onde você pode baixá-la com
    javascript.

Exemplo:

 $exports = new ReportsExporter($data, $columns);
  Excel::store($exports , 'filename.xlsx', 'custom_disk_location');

defina a localização do seu disco personalizado no sistema de arquivos de configuração como este

'custom_disk_location' => [
            'driver' => 'local',
            'root' => public_path('files'),
        ],
...

isso irá garantir que o arquivo excel não seja salvo no armazenamento / aplicativo
mas irá salvá-lo no caminho público / arquivos em seu servidor

de volta ao seu javascript, baixe o arquivo assim

function download(filename, path) {
        let element = document.createElement('a');
        element.setAttribute('href', path);
        element.setAttribute('download', filename);

        element.style.display = 'none';
        document.body.appendChild(element);

        element.click();

        document.body.removeChild(element);
    }

chame a função de download passando o nome do arquivo e o caminho
download ("nomedoarquivo.xlsx", localização.origin + "arquivos / nomedoarquivo.xlsx");

após o download lembre-se de voltar ao servidor e remover o que está armazenado no servidor desta forma
desvincular ("arquivos / nomedoarquivo.xlsx");

Espero que isso ajude quem está achando difícil baixar laravel-excel através de ajax ou javascript.
Esta é a melhor opção, pois oferece mais flexibilidade para personalizar sua experiência de usuário e
forneça feedback sobre o status do download, bem como nomeie seu arquivo da maneira que desejar.

Eu precisava devolver um xlsx do ajax, então ajustei um pouco novamente e acabei com isso:

PHP
$ data é uma consulta do Eloquent convertida em Array.

$myFile= Excel::create("filename", function($excel) use($data) {
   $excel->setTitle('title');
   $excel->sheet('sheet 1', function($sheet) use($data) {
     $sheet->fromArray($data, null, 'A1', true, true);
   });
});

$myFile = $myFile->string('xlsx'); //change xlsx for the format you want, default is xls
$response =  array(
   'name' => "filename", //no extention needed
   'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".base64_encode($myFile) //mime type of used format
);
return response()->json($response);

js

$.ajax({
      cache: false,
      url: url, //GET route 
      data:  params, //your parameters data here
      success: function (response, textStatus, request) {
        var a = document.createElement("a");
        a.href = response.file; 
        a.download = response.name;
        document.body.appendChild(a);
        a.click();
        a.remove();
      },
      error: function (ajaxContext) {
        toastr.error('Export error: '+ajaxContext.responseText);
      }
    });

Eu precisava devolver um xlsx do ajax, então ajustei um pouco novamente e acabei com isso:

PHP
$ data é uma consulta do Eloquent convertida em Array.

$myFile= Excel::create("filename", function($excel) use($data) {
   $excel->setTitle('title');
   $excel->sheet('sheet 1', function($sheet) use($data) {
     $sheet->fromArray($data, null, 'A1', true, true);
   });
});

$myFile = $myFile->string('xlsx'); //change xlsx for the format you want, default is xls
$response =  array(
   'name' => "filename", //no extention needed
   'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,".base64_encode($myFile) //mime type of used format
);
return response()->json($response);

js

$.ajax({
      cache: false,
      url: url, //GET route 
      data:  params, //your parameters data here
      success: function (response, textStatus, request) {
        var a = document.createElement("a");
        a.href = response.file; 
        a.download = response.name;
        document.body.appendChild(a);
        a.click();
        a.remove();
      },
      error: function (ajaxContext) {
        toastr.error('Export error: '+ajaxContext.responseText);
      }
    });

tão bom

Esta página foi útil?
0 / 5 - 0 avaliações