美文网首页
使用file-saver导出文件

使用file-saver导出文件

作者: 隔壁老王z | 来源:发表于2021-09-01 14:40 被阅读0次
import FileSaver from 'file-saver'

/**
 * 导出csv
 * @param {Array<Object>} data  // 导出的数据
 * @param {String} fileName // 文件名
 * @param {Array<String>} columns  // 表头对应的字段
 * @param {Array<String>} headers  // 表头名称,不传则为columns
 */
export const saveDataAsCsv = function(data, fileName, columns, headers) {
  const prefix = '\uFEFF'
  const rowDelimiter = '\n' // 默认行分隔符 '\n'
  if (!headers) headers = columns
  let exportContent = prefix + headers.join(',') + '\n'
  for (const i in data) {
    for (const c in columns) {
      let col = (data[i][columns[c]] + '') || ' '
      col = col.replace(new RegExp(rowDelimiter, 'g'), ' ')
      exportContent += `"\t${col}",`
    }
    exportContent += '\n'
  }
  const blob = new Blob([exportContent], { type: 'text/csv;charset = utf-8' })
  FileSaver.saveAs(blob, fileName)
}
// 例子
saveDataAsCsv([{ name: '章三', age: 10 }], 'data.csv', ['name', 'age'], ['名字', '年龄'])

主要是注意处理文本中有换行符 '\n', 列分割符 ','的情况

/**
 * 导出json
 * @param {Object | Array} json  // 导出的json
 * @param {String} fileName // 文件名
 */
export const saveDataAsJson = function(json, fileName) {
  const blob = new Blob([JSON.stringify(json, null, 2)], { type: 'text/plain;charset = utf-8' })
  FileSaver.saveAs(blob, fileName, { autoBom: false })
}

不设置 autoBom: false的话导出的文本有些程序可能会识别不了

相关文章

网友评论

      本文标题:使用file-saver导出文件

      本文链接:https://www.haomeiwen.com/subject/jubxwltx.html