[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打开下载文件中中文乱码的问题