# 生成excel

# 开始

使用了
npm i xlsx -S 链接 (opens new window)
npm i file-saver -S 链接 (opens new window)

# 导出表格方式--table_to_book

这种方式直接把表格中的内容直接导出

 <Table
             class="border_0"
             :loading="loading"
             :border="false"
             :columns="columns_vary"
             :data="data"
             ref="table"
             id="fleet_admin_table">
import FileSaver from "file-saver";

var xlsxParam = {
  raw: true
};
var wb = XLSX.utils.table_to_book(
  document.querySelector("#fleet_admin_table"),
  xlsxParam
);
var wbout = XLSX.write(wb, {
  bookType: "xlsx",
  bookSST: true,
  type: "array",
});
try {
  let fileName = "export.xlsx";
  FileSaver.saveAs(
    new Blob([wbout], {
      type: "application/octet-stream;charset=utf-8",
    }),
    fileName
  );
} catch (e) {
  if (typeof console !== "undefined") console.log(e, wbout);
}
return wbout;

# 手动生成数据导出Excel--aoa_to_sheet

// 将一个sheet转成最终的excel文件的blob对象,然后利用URL.createObjectURL下载
function sheet2blob(sheet, sheetName) {
  sheetName = sheetName || 'sheet1';
  var workbook = {
    SheetNames: [sheetName],
    Sheets: {}
  };
  workbook.Sheets[sheetName] = sheet;
  // 生成excel的配置项
  var wopts = {
    // 要生成的文件类型
    bookType: 'xlsx',
    // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
    bookSST: false,
    type: 'binary'
  };
  var wbout = XLSX.write(workbook, wopts);
  var blob = new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  });
  // 字符串转ArrayBuffer
  function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
  return blob;
}

// 保存Excel
function openDownloadDialog(url, saveName) {
  if (typeof url == 'object' && url instanceof Blob) {
    // 创建blob地址
    url = URL.createObjectURL(url);
  }
  var aLink = document.createElement('a');
  aLink.href = url;
  // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
  aLink.download = saveName || '';
  var event;
  if (window.MouseEvent) event = new MouseEvent('click');
  else {
    event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  }
  aLink.dispatchEvent(event);
}

var aoa = [
	['姓名', '性别', '年龄', '注册时间'],
	['张三', '男', 18, new Date()],
	['李四', '女', 22, new Date()]
];
var sheet = XLSX.utils.aoa_to_sheet(aoa);
openDownloadDialog(sheet2blob(sheet), '导出.xlsx');

# 对象输出表格--json_to_sheet

//待展示的数据,可能是从后台返回的json数据或者是自己定义的object
const data = [
  { S:1, h:2, e:3, e_1:4, t:5, J:6, id:7 },
  { S:2, h:3, e:4, e_1:5, t:6, J:7, id:8 }
];
 
//展示的顺序,把data中对象的属性按照你想要的顺序排放就可以了,我这里把id移到了第一列展示
const header = ["id", "S","h","e","e_1","t","J"];
 
var worksheet = XLSX.utils.json_to_sheet(data, {header:header});

image.png
也可以自定义表头

//待展示的数据,可能是从后台返回的json数据或者是自己定义的object
const data = [
  { S:1, h:2, e:3, e_1:4, t:5, J:6, id:7 },
  { S:2, h:3, e:4, e_1:5, t:6, J:7, id:8 }
];
 
//展示的顺序,把data中对象的属性按照你想要的顺序排放就可以了,我这里把id移到了第一列展示
const header = ["id", "S","h","e","e_1","t","J"];
//展示的名称
const headerDisplay = {S:"S栏", h:"h栏", e:"e栏", e_1:"e_1栏", t:"t栏", J:"J栏", id:"id栏"};
 
//将表头放到原始数据里面去,要保证表头在数组的最前面
const newData = [headerDisplay, ...data];
 
//加了一句skipHeader:true,这样就会忽略原来的表头
var worksheet = XLSX.utils.json_to_sheet(newData, {header:header, skipHeader:true});

image.png

# 总结

  • aoa_to_sheet: 这个工具类最强大也最实用了,将一个二维数组转成sheet,会自动处理number、string、boolean、date等类型数据;
  • table_to_sheet: 将一个table dom直接转成sheet,会自动识别colspanrowspan并将其转成对应的单元格合并;
  • json_to_sheet: 将一个由对象组成的数组转成sheet;

  • sheet_to_csv:生成CSV格式``
  • sheet_to_txt:生成纯文本格式
  • sheet_to_html:生成HTML格式``
  • sheet_to_json:输出JSON格式

image.png