Laravel-excel: 방법: ajax만 μ‚¬μš©ν•˜μ—¬ csv/xls 파일 μ €μž₯

에 λ§Œλ“  2016λ…„ 07μ›” 14일  Β·  12μ½”λ©˜νŠΈ  Β·  좜처: Maatwebsite/Laravel-Excel

μ•ˆλ…•ν•˜μ„Έμš” μ—¬λŸ¬λΆ„,

λ‚˜λŠ” 우리 쀑 일뢀가 ajax μš”μ²­μ—μ„œ νŒŒμΌμ„ μ œκ³΅ν•˜λ €κ³  ν•˜λŠ” 것을 λ³΄μ•˜μŠ΅λ‹ˆλ‹€. μ•½κ°„μ˜ 연ꡬ 후에, λ‚˜λŠ” 그것을 ν•  λͺ…ν™•ν•œ 해결책을 찾지 λͺ»ν–ˆμŠ΅λ‹ˆλ‹€. κ·Έ 쀑 일뢀λ₯Ό μ‘°μ •ν•˜μ—¬ Ajax μš”μ²­μ—μ„œ csv 및 xls 데이터λ₯Ό μ„±κ³΅μ μœΌλ‘œ λ‚΄λ³΄λƒˆμŠ΅λ‹ˆλ‹€. λ¬Έμ œλŠ” 파일 ν˜•μ‹μ΄ xls인 경우 인코딩 λ•Œλ¬Έμ— μ‘°μž‘μ΄ λ‹€λ₯΄λ―€λ‘œ μ•½κ°„μ˜ 쑰정이 μžˆλ‹€λŠ” κ²ƒμž…λ‹ˆλ‹€.

λ°μ΄ν„°λŠ” Array둜 λ³€ν™˜λœ 일반적인 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);
      }
    });

μΆ”μ‹ : 이것은 λ¬Έμ œκ°€ μ•„λ‹™λ‹ˆλ‹€

κ°€μž₯ μœ μš©ν•œ λŒ“κΈ€

ajaxμ—μ„œ xlsxλ₯Ό λ°˜ν™˜ν•΄μ•Ό ν–ˆκΈ° λ•Œλ¬Έμ— λ‹€μ‹œ μ•½κ°„ μ‘°μ •ν–ˆκ³  λ‹€μŒκ³Ό 같이 λλ‚©λ‹ˆλ‹€.

PHP
$dataλŠ” Array둜 λ³€ν™˜λœ Eloquent μΏΌλ¦¬μž…λ‹ˆλ‹€.

$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μ—μ„œλŠ” μž‘λ™ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.

ajaxμ—μ„œ xlsxλ₯Ό λ°˜ν™˜ν•΄μ•Ό ν–ˆκΈ° λ•Œλ¬Έμ— λ‹€μ‹œ μ•½κ°„ μ‘°μ •ν–ˆκ³  λ‹€μŒκ³Ό 같이 λλ‚©λ‹ˆλ‹€.

PHP
$dataλŠ” Array둜 λ³€ν™˜λœ Eloquent μΏΌλ¦¬μž…λ‹ˆλ‹€.

$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 λ‚΄κ°€ λ§ν–ˆλ“―μ΄ μ›λž˜ 닡변을 "μˆ˜μ •"ν•˜κ³  ν•„μš”ν•˜μ§€ μ•Šμ€ 것을 μ œκ±°ν•˜κ³  μ»΄νŒ©νŠΈν•˜κ²Œ λ§Œλ“€κ³  MIME μœ ν˜•μ˜ ms office xlsx ν™•μž₯을 μœ„ν•œ duckduckgo(검색 엔진), λ‚˜λŠ” ν™•μ‹ ν•˜μ§€ λͺ»ν–ˆμŠ΅λ‹ˆλ‹€. λ‚΄κ°€ 그것을 μ‹œλ„ ν•  λ•ŒκΉŒμ§€ μž‘λ™ν•˜μ§€λ§Œ κ²Œμ‹œν•˜κΈ° 전에 μ‹œλ„ν–ˆκ³  μž‘λ™ν–ˆκΈ° λ•Œλ¬Έμ— λˆ„κ΅°κ°€κ°€ μœ μš©ν•˜λ‹€κ³  생각할 경우λ₯Ό λŒ€λΉ„ν•˜μ—¬ κ²Œμ‹œν–ˆμŠ΅λ‹ˆλ‹€.

λ‚˜λŠ” μžλ°” 슀크립트 λ‚˜ μ•„μ•½μŠ€κ°€ μ „ν˜€ ν•„μš”ν•˜μ§€ μ•Šλ‹€λŠ” 것을 λ°œκ²¬ν–ˆμŠ΅λ‹ˆλ‹€. λ‹€μ–‘ν•œ csv/xls/xlsx νŒŒμΌμ„ λ‹€μš΄λ‘œλ“œν•  수 μžˆλŠ” 링크가 μžˆλŠ” μ›Ή νŽ˜μ΄μ§€κ°€ μžˆλŠ”λ° νŽ˜μ΄μ§€λ₯Ό μƒˆλ‘œ 고치고 싢지 μ•ŠμŠ΅λ‹ˆλ‹€. λ‚΄κ°€ ν•œ λͺ¨λ“  것은 λ‹€μŒμ„ λ°˜ν™˜ν•˜λŠ” μž‘μ—…μ— 링크λ₯Ό μ—°κ²°ν•˜λŠ” κ²ƒμž…λ‹ˆλ‹€ ...

곡개 ν•¨μˆ˜ getSpreadsheet() {
$items = ν•­λͺ©::all();
Excel::create('items', function($excel) use($items) {
$excel->sheet('내보내기 파일', function($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년에도 이 λ¬Έμ œκ°€ 계속 λ°œμƒν•˜λŠ” 경우 Laravel Excel의 버전 3.xκ°€ λ³€κ²½λ˜μ—ˆμœΌλ―€λ‘œ 여기에 해결책이 μžˆμŠ΅λ‹ˆλ‹€.

  1. Ajaxλ₯Ό 톡해 Laravel Excel κ°œμ²΄μ™€ μƒν˜Έ μž‘μš©ν•˜λŠ” 컨트둀러둜 데이터λ₯Ό λ³΄λƒ…λ‹ˆλ‹€.
  2. Laravel Excel κ°œμ²΄κ°€ 데이터λ₯Ό λΈ”λ ˆμ΄λ“œ 보기둜 보내도둝 ν•˜μ‹­μ‹œμ˜€.
  3. λΈ”λ ˆμ΄λ“œ 보기λ₯Ό μ„œλ²„μ— μ €μž₯
  4. jsλ₯Ό μ‚¬μš©ν•˜μ—¬ μ„œλ²„μ— νŒŒμΌμ„ λ‹€μš΄λ‘œλ“œν•©λ‹ˆλ‹€.
    λ”°λΌμ„œ μ•„μ΄λ””μ–΄λŠ” λΈ”λ ˆμ΄λ“œ 보기λ₯Ό Excel둜 내보내고 λ‹€μš΄λ‘œλ“œν•  수 μžˆλŠ” λ””μŠ€ν¬ μœ„μΉ˜μ— μ €μž₯ν•˜λŠ” κ²ƒμž…λ‹ˆλ‹€.
    μžλ°”μŠ€ν¬λ¦½νŠΈ.

μ˜ˆμ‹œ:

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

λ‹€μŒκ³Ό 같이 ꡬ성 파일 μ‹œμŠ€ν…œμ—μ„œ μ‚¬μš©μž μ •μ˜ λ””μŠ€ν¬ μœ„μΉ˜λ₯Ό μ •μ˜ν•˜μ‹­μ‹œμ˜€.

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

μ΄λ ‡κ²Œ ν•˜λ©΄ Excel 파일이 μ €μž₯μ†Œ/앱에 μ €μž₯λ˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.
κ·ΈλŸ¬λ‚˜ μ„œλ²„μ˜ 곡개/파일 κ²½λ‘œμ— μ €μž₯ν•©λ‹ˆλ‹€.

μžλ°” 슀크립트둜 λŒμ•„κ°€μ„œ λ‹€μŒκ³Ό 같은 νŒŒμΌμ„ λ‹€μš΄λ‘œλ“œν•˜μ‹­μ‹œμ˜€.

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

파일 이름과 경둜λ₯Ό μ „λ‹¬ν•˜μ—¬ λ‹€μš΄λ‘œλ“œ κΈ°λŠ₯을 ν˜ΈμΆœν•©λ‹ˆλ‹€.
λ‹€μš΄λ‘œλ“œ("파일λͺ….xlsx", location.origin+"파일λͺ…/파일λͺ….xlsx");

λ‹€μš΄λ‘œλ“œ ν›„ μ„œλ²„λ‘œ λŒμ•„κ°€μ„œ λ‹€μŒκ³Ό 같이 μ„œλ²„μ— μ €μž₯된 것을 μ œκ±°ν•˜λŠ” 것을 μžŠμ§€ λ§ˆμ‹­μ‹œμ˜€.
unlink("파일/파일λͺ….xlsx");

이것이 ajax λ˜λŠ” javascriptλ₯Ό 톡해 laravel-excel을 λ‹€μš΄λ‘œλ“œν•˜κΈ° μ–΄λ €μš΄ μ‚¬λžŒμ—κ²Œ 도움이 되기λ₯Ό λ°”λžλ‹ˆλ‹€.
이것은 μ‚¬μš©μž κ²½ν—˜μ„ μ‚¬μš©μžν™”ν•  수 μžˆλŠ” 더 λ§Žμ€ μœ μ—°μ„±μ„ μ œκ³΅ν•˜κ³ 
λ‹€μš΄λ‘œλ“œ μƒνƒœμ— κ΄€ν•œ ν”Όλ“œλ°±μ„ μ œκ³΅ν•˜κ³  μ›ν•˜λŠ” λ°©μ‹μœΌλ‘œ 파일 이름을 μ§€μ •ν•©λ‹ˆλ‹€.

ajaxμ—μ„œ xlsxλ₯Ό λ°˜ν™˜ν•΄μ•Ό ν–ˆκΈ° λ•Œλ¬Έμ— λ‹€μ‹œ μ•½κ°„ μ‘°μ •ν–ˆκ³  λ‹€μŒκ³Ό 같이 λλ‚©λ‹ˆλ‹€.

PHP
$dataλŠ” Array둜 λ³€ν™˜λœ Eloquent μΏΌλ¦¬μž…λ‹ˆλ‹€.

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

ajaxμ—μ„œ xlsxλ₯Ό λ°˜ν™˜ν•΄μ•Ό ν–ˆκΈ° λ•Œλ¬Έμ— λ‹€μ‹œ μ•½κ°„ μ‘°μ •ν–ˆκ³  λ‹€μŒκ³Ό 같이 λλ‚©λ‹ˆλ‹€.

PHP
$dataλŠ” Array둜 λ³€ν™˜λœ Eloquent μΏΌλ¦¬μž…λ‹ˆλ‹€.

$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 λ“±κΈ‰