import * as XLSX from "xlsx";


export const exportExcel = (dataSource, columns, fileName = "excel", sheetName = "") => {

  let excelTitle = [];
  let dataTitle = [];
  let data = [];
  if (columns.length == 0) {
    throw "输出列为空";
  } else if (dataSource.length == 0) {
    throw "数据源为空";
  } else {
    for (let i in columns) {
      excelTitle.push(columns[i].label);
      dataTitle.push(columns[i].name);
    }

    let keys = Object.keys(dataSource[0]);
    for (let k of dataTitle) {
      if (keys.indexOf("k") == -1) {
        throw "数据源中不存在列：" + k;
      }
    }
  }

  data.push(excelTitle);//第一行为列名

  for (let row of dataSource) {
    let newRow = [];
    for (let i in dataTitle) {
      newRow.push(row[dataTitle[i]] ? row[dataTitle[i]] : "");
    }
    data.push(newRow);
  }

  const ws = XLSX.utils.aoa_to_sheet(data);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, sheetName);
  XLSX.writeFile(wb, fileName + ".xlsx");
};
