coffeescript實現nodejs前端csv文件下載

[There's a nicer way.]


代碼段如下:

# alllw the browser to create a CSV file and download it.
# _arrays = [[..], [..],.., [..]]
# ps: "\uFEFF" to solve the problem of wrong display of chinese in excel

module.exports =
  csv: (_filename, _arrays)->
    # store data into a string
    _str = ''
    for _arr in _arrays
      _line = ''
      for _index in _arr
        _line += ',' if _line isnt ''
        _line += _index
      _str += _line + '\r\n'

    # create the click to download csv file
    _a = $('<a class="hide">點擊下載</a>')
    _a.attr "download", "#{_filename}.csv"
    blob = new Blob ["\uFEFF" + _str], {'type':'application\/octet-stream'}
    _a.attr "href", window.URL.createObjectURL(blob)
    $("body").append _a
    _a[0].click()
    setTimeout ->
      _a.remove()
    , 1000

ps

(1)arrays爲傳入的參數,其中包含多個array,每個代表csv的一行數據,第一行爲標題行

(2)整個過程分爲兩部分,一是將arrays中的數據傳入到_str中,變成一個字符串;第二個部分是添加一個下載按鈕並觸發,下載相應文件,Blob(binary large object)爲一種二進制大對象類型

(3)\uFEFF解決了excel打開下載文件中中文亂碼的問題



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章