数据导出excel文件

插件:SheetJS

简单过程:数据转sheet,添加到workbook,生成excel文件的Blob对象然后下载

const data = [
  ['id', 'name', 'age'],
  ['1', '小明', '12']
];

const createSheet = (data) => {
  return XLSX.utils.aoa_to_sheet(data);
}

const createWorkbook = (sheet) => {
  const wb = {
    SheetNames: ['Sheet1'],
    Sheets: {}
  };

  const option = {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary'
  };

  wb.Sheets.Sheet1 = sheet;

  return XLSX.write(wb, option);
}

data数组第一个是表头内容,一个workbook(工作簿)可能有多个表(Sheet),这里简单的就写了一个,所有数据都在这个表里

const stringToArrayBuffer = (strings) => {
  const length = strings.length;

  const buffer = new ArrayBuffer(length);
  const view = new Uint8Array(buffer);

  for (let i = 0; i !== length; i += 1) {
    view[i] = strings.charCodeAt(i) & 0xFF
  }

  return buffer;
}

const dataToBlob = (data) => {
  return new Blob([stringToArrayBuffer(data)], {
    type: 'application/octet-stream'
  })
}

ArrayBuffer对象代表通用的、固定长度的原始二进制数据缓冲区,不能直接操作,需要通过TypedArray视图或DataView视图才能读写,new ArrayBuffer传入参数表示创建的字节数
视图用于以指定格式解读二进制数据,Uint8Array是TypedArray的一种,表示无符号8位整数
Blob 对象表示一个不可变、原始数据的类文件对象

const createDownload = (blob, filename = 'test.xlsx') => {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  document.body.appendChild(a);

  const event = const event = new MouseEvent('click');
  a.dispatchEvent(event);
}

const sheet = createSheet(data);
const workbook = createWorkbook(sheet);
const blob = dataToBlob(workbook);
createDownload(blob)

URL.createObjectURL创建代表参数对象的URL,a标签的download属性指示浏览器下载url,属性值作为文件下载保存的文件名,生成MouseEvent对象可以用鼠标事件 - Web API 接口参考 | MDN,或者是:

  const event = document.createEvent('MouseEvents');
  event.initEvent('click', true, true);

或者直接使用GitHub - eligrey/FileSaver.js: An HTML5 saveAs() FileSaver implementation

saveAs(blob, 'filename.xlsx')

备注: IE10以下不支持Blob对象,IE不支持MouseEvent构造函数

Comments
Write a Comment