Laravel-excel: Как: сохранять файлы csv / xls, используя только ajax

Созданный на 14 июл. 2016  ·  12Комментарии  ·  Источник: Maatwebsite/Laravel-Excel

Привет, народ,

Я видел, что некоторые из нас пытаются обслуживать файл из запроса ajax. После некоторого исследования я не нашел четкого решения для этого. Настраивая некоторые из них, я успешно экспортировал данные csv и xls из запроса Ajax. Дело в том, что манипуляции с типом файла xls отличаются из-за кодировки, так что есть небольшие изменения.

Данные поступают из типичного запроса Eloquent, преобразованного в массив:

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);
      }
    });

пс: это не проблема

Самый полезный комментарий

Мне нужно было вернуть xlsx из ajax, поэтому я немного поправил, и вот что у меня получилось:

PHP
$ data - это красноречивый запрос, преобразованный в массив.

$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);
      }
    });

Все 12 Комментарий

Большое спасибо, он хорошо работает для CSV, но не для xls,

Мне нужно было вернуть xlsx из ajax, поэтому я немного поправил, и вот что у меня получилось:

PHP
$ data - это красноречивый запрос, преобразованный в массив.

$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);
      }
    });

Благодарность!!

Я получаю сообщение об ошибке «Класс« Excel »не найден». Не могли бы вы мне помочь?

@randomhoodie из любого источника, как вы пришли с этим решением?

@eldyvoon, как я уже сказал: "Я подправил" исходный ответ, уберите то, что мне не нужно, сделайте его компактным и duckduckgo (поисковая система) для mime-типа расширения ms office xlsx, я не был уверен, что это было будет работать, пока я не попробовал, но я пробовал это перед публикацией, и, поскольку он работал, я опубликовал его на случай, если кто-то сочтет это полезным.

Я обнаружил, что ни javascript, ни ajax не нужны вообще. У меня есть веб-страница со ссылками для загрузки кучи разных файлов csv / xls / xlsx, и я не хочу, чтобы страница обновлялась вообще. Все, что я сделал, это подключил ссылку к действию, которое вернуло следующее ...

публичная функция getSpreadsheet () {
$ items = Item :: all ();
Excel :: create ('items', function ($ excel) use ($ items) {
$ excel-> sheet ('ExportFile', функция ($ sheet) use ($ items) {
$ sheet-> fromArray ($ items);
});
}) -> экспорт ('xls');
}

Замечательно !!!!

Спасибо @randomhoodie!

Для пакета 3.x я бы обновил ваш PHP примерно так, согласно руководству по

        $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);

Спасибо @kynetiv , я использую версию 3.x, но мне нужно было поставить расширение, например: filename.xlsx

Если у вас все еще есть эта проблема в 2020 году. Обратите внимание, что версия 3.x Laravel excel была изменена, поэтому вот решение

  1. Отправьте свои данные через Ajax на ваш контроллер, который взаимодействует с объектом Laravel Excel.
  2. Позвольте объекту Laravel excel отправлять ваши данные в представление лезвия
  3. Сохраните представление лезвия на сервере
  4. используйте js для загрузки файла на сервер.
    Итак, идея состоит в том, чтобы экспортировать представление лезвия как excel и сохранить его на диске, где вы можете загрузить его с помощью
    javascript.

Пример:

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

определите свое собственное расположение на диске в файловой системе конфигурации, как это

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

это гарантирует, что файл Excel не будет сохранен в хранилище / приложении
но сохранит его в пути public / files на вашем сервере

вернитесь к вашему javascript, загрузите файл следующим образом

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);
    }

вызвать функцию загрузки, передав имя файла и путь
скачать ("filename.xlsx", location.origin + "files / filename.xlsx");

после загрузки не забудьте вернуться на сервер и удалить тот, который хранится на сервере, как это
unlink ("файлы / имя_файла.xlsx");

Надеюсь, это поможет любому, кому сложно загрузить laravel-excel через ajax или javascript.
Это лучший вариант, поскольку он дает вам больше гибкости для настройки вашего взаимодействия с пользователем и
дайте им обратную связь относительно статуса загрузки, а также назовите файл так, как вам нравится.

Мне нужно было вернуть xlsx из ajax, поэтому я немного поправил, и вот что у меня получилось:

PHP
$ data - это красноречивый запрос, преобразованный в массив.

$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);
      }
    });

Мне нужно было вернуть xlsx из ajax, поэтому я немного поправил, и вот что у меня получилось:

PHP
$ data - это красноречивый запрос, преобразованный в массив.

$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);
      }
    });

так хорошо

Была ли эта страница полезной?
0 / 5 - 0 рейтинги