1. 程式人生 > >匯出Excel功能-從服務端到瀏覽器的簡單處理

匯出Excel功能-從服務端到瀏覽器的簡單處理

服務端定義一個匯出功能的關鍵程式碼

Java 定義一個export的功能函式,以下為關鍵程式碼(介面中的一部分處理邏輯):

@Override
public byte[] export(String startdate, String enddate, Integer type, String name,
 HttpServletResponse response) {
    // other logic omitted here ...

    // set response args,it used for open download
    response.reset();
    response.setContentType("application/vnd.ms-excel;charset=utf-8"
); try { response.setHeader("Content-Disposition", "attachment;filename=" + new String((name+ ".xls").getBytes(), "iso-8859-1")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } ByteArrayOutputStream output = new ByteArrayOutputStream(); try
{ workList.write(output); // write } catch (IOException e) { e.printStackTrace(); } return output.toByteArray(); }

前端處理,方式1:使用ng1實現,在自定義指令中來通過介面接收資料流 [ 存在相容問題的方式 ]

指令如下:

angular.module('yourNgApp')
    .directive('sysExport', function ($http, $document) {
        return
{ templateUrl: "app/system/export/export.directive.html", restrict: 'EA', replace: true, scope: { item: '=' }, link: function (scope, element) { // 訪問請求的函式 function getExport(postData) { // 拼出自己的url var url = '/api/course/export?startdate=' + postData.startdate + '&enddate=' + postData.enddate + '&type=' + postData.type + '&name=' + postData.name; // 注意下面的responseType 一定要有哦! var finalPostData = { url: url, method: 'POST', responseType: "arraybuffer", headers: {'Content-type': 'application/json'} }; $http(finalPostData) .success(function (data) { var blob, fileName, blobArgs; blobArgs = {type: 'application/vnd.ms-excel application/x-excel'}; blob = new Blob([data], blobArgs); var a = $document[0].createElement('a'); a.download = postData.name + '.xls'; a.href = URL.createObjectURL(blob); a.click(); }) .error(function (e) { console.log(e); }); } element.on('click', function () { getExport(scope.item); }); } }; });

至此可實現通過指令的點選事件來下載excel格式了。
因為匯出功能多用於後臺管理,適用性不是很普遍,所以相容問題可協商,所以前臺使用了Blob物件。
為了節約伺服器資源可通過此種方式通過點選來下載,而不是將匯出的檔案單獨存放到伺服器上通過返回excel所在的url地址來進行下載。

前端處理,方式2:直接通過a連結訪問,[相容性好]

<a href="/api/course/export?startdate={{cl.startdate}}&enddate={{cl.enddate}}&type={{cl.type}}&name={{cl.name}}" class="btn btn-success">匯出</a>

擴充套件

總結:

上面前端用到的都是一些H5高階API 適用性不是很高, 但也臨時解決了一些問題,只作為嘗試 :)

通過a連結的方式請求, 直接在伺服器端完成檔案的操作,點選後直接下載,相容良好,但不適合大檔案的傳輸下載。