tools.js 8.42 KB

import XLSX2 from "xlsx";
import XLSX from "xlsx-style";
/**
 * 获取数据类型
 * @param {All} [o] 需要检测的数据
 * @returns {String}
 */
export function getType (o) {
  return Object.prototype.toString.call(o).slice(8, -1);
}
/**
 * 判断是否是指定数据类型
 * @param {All} [o] 需要检测的数据
 * @param {String} [type] 数据类型
 * @returns {Boolean}
 */
export function isKeyType (o, type) {
  return getType(o).toLowerCase() === type.toLowerCase();
}
export function deepCopy (sth) {
  let copy;
  if (null == sth || "object" != typeof sth) return sth;
  if (isKeyType(sth, 'date')) {
    copy = new Date();
    copy.setTime(sth.getTime());
    return copy;
  }
  if (isKeyType(sth, 'array')) {
    copy = [];
    for (let i = 0, len = sth.length; i < len; i++) {
      copy[i] = deepCopy(sth[i]);
    }
    return copy;
  }
  if (isKeyType(sth, 'object')) {
    copy = {};
    for (let attr in sth) {
      if (sth.hasOwnProperty(attr)) copy[attr] = deepCopy(sth[attr]);
    }
    return copy;
  }
  return null;
}
/**
 * 关键信息隐藏
 * @param str 字符串
 * @param frontLen 字符串前面保留位数
 * @param endLen 字符串后面保留位数
 * @returns {string}
 */
export function hideCode (str, frontLen, endLen = 0) {
  var len = str.length - frontLen - endLen;
  var xing = '';
  for (var i = 0; i < len; i++) {
    xing += '*';
  }
  return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
};
// 数组去重

export function unique (arr) {
  var obj = {};
  return arr.filter(function (item, index, arr) {
    return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
  })
}
// 创造id

export function getUuid (len, radix) {
  var chars = "0123456789abcdefghijklmnopqrstuvwxyz".split(
    ""
  );
  var uuid = [],
    i;
  radix = radix || chars.length;
  if (len) {
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
  } else {
    var r;
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
    uuid[14] = "4";
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16);
        uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
      }
    }
  }
  return uuid.join("");
}

//js计算两个时间戳之间的时间差 (月)
export function intervalTime (startTime, endTime) {
  // var timestamp=new Date().getTime(); //计算当前时间戳
  var timestamp = (Date.parse(new Date())) / 1000;//计算当前时间戳 (毫秒级)
  var date1 = ""; //开始时间
  if (timestamp < startTime) {
    date1 = startTime;
  } else {
    date1 = timestamp; //开始时间
  }
  var date2 = endTime; //结束时间
  // var date3 = date2.getTime() - date1.getTime(); //时间差的毫秒数
  var date3 = (date2 - date1) * 1000; //时间差的毫秒数
  //计算出相差天数
  var mon = Math.floor(date3 / (30 * 24 * 3600 * 1000 * 1000));
  // return   days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒"
  return mon
}
// 日期转时间戳
export function js_strto_time (str_time) {
  var str = str_time.replace(/-/g, '/') // 将-替换成/,因为下面这个构造函数只支持/分隔的日期字符串
  var date = new Date(str) // 构造一个日期型数据,值为传入的字符串
  return date.getTime()
}
// 时间戳转日期 
export function timestampToTime (timestamp) {
  var date = new Date(timestamp)//时间戳为10位需*1000,时间戳为13位的话不需乘1000
  var Y = date.getFullYear() + '-'
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  var D = date.getDate() > 10 ? date.getDate() : '0' + date.getDate()
  return Y + M + D
}


function formatDate (value) {
  var date = new Date(value);
  var y = date.getFullYear(),
    m = date.getMonth() + 1,
    d = date.getDate()
  if (m < 10) { m = '0' + m; }
  if (d < 10) { d = '0' + d; }
  var t = y + '-' + m + '-' + d
  return t;
}

export function getCurrentDate (date = 'firstDay') {
  var now = new Date() // 当前日期
  var nowYear = now.getFullYear() //当前年
  var nowMonth = now.getMonth() //当前月 (值为0~11)
  var d = now.getDate() //当天
  if (date == 'firstDay') {
    return formatDate(new Date(nowYear, nowMonth, 1))  // 本月开始时间
  } else {
    return formatDate(new Date(nowYear, nowMonth + 1, 0)) // 本月结束时间
  }
}

export function setExport2Excel (exportName) {
  /* generate workbook object from table */
  var wb = XLSX2.utils.table_to_sheet(document.querySelector("#mytable"));//mytable为表格的id名
  if (!wb['!merges']) {
    this.$message.warning('无法导出:报表无数据');
    return
  }
  for (var i = 0; i < 11; i++) {
    wb["!cols"][i] = { wpx: 150 }
  }
  // 样式的文档地址
  // https://www.npmjs.com/package/xlsx-style
  for (const key in wb) {
    if (key == 'A1') {
      wb[key].s = {
        font: {//字体设置
          sz: 24,
          bold: true,
        },
        alignment: {//文字居中
          horizontal: 'center',
          vertical: 'center',
          wrapText: 1,
          indent: 0,
          wrap_text: true
        }
      }
    } else if (key.indexOf('!') === -1 && wb[key].v) {
      wb[key].s = {
        font: {//字体设置
          sz: 13,
          bold: false,
          color: {
            rgb: '000000'//十六进制,不带#
          }
        },
        alignment: {//文字居中
          horizontal: 'center',
          vertical: 'center',
          wrapText: 1,
          indent: 0,
          wrap_text: true
        },
        border: { // 设置边框
          top: { style: 'thin' },
          bottom: { style: 'thin' },
          left: { style: 'thin' },
          right: { style: 'thin' }
        }
      }
    }
  }
  var data = addRangeBorder(wb['!merges'], wb) //合并项添加边框
  var filedata = sheet2blob(data)
  openDownloadDialog(filedata, exportName + ".xlsx")
}
//为合并项添加边框
function addRangeBorder (range, ws) {
  let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

  range.forEach(item => {
    let startColNumber = Number(item.s.r), endColNumber = Number(item.e.r);
    let startRowNumber = Number(item.s.c), endRowNumber = Number(item.e.c);
    const test = ws[arr[startRowNumber] + (startColNumber + 1)];
    for (let col = startColNumber; col <= endColNumber; col++) {
      for (let row = startRowNumber; row <= endRowNumber; row++) {
        ws[arr[row] + (col + 1)] = test;
      }
    }
  })
  return ws;
}
//将一个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', // 要生成的文件类型
    bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
    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;
}
function openDownloadDialog (url, saveName) {
  if (typeof url == 'object' && url instanceof Blob) {
    url = URL.createObjectURL(url); // 创建blob地址
  }
  var aLink = document.createElement('a');
  aLink.href = url;
  aLink.download = saveName || ''; // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
  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);
}


function judgeObjectComplete (ObjectValue) {
  let flag = new Boolean()
  flag = true
  for (let key in ObjectValue) {
    if (ObjectValue[key]) { } else {
      flag = false
    }
  }
  if (!flag) {
    return false
  } else {
    return true
  }
}
export function judgeListComplete (list) {
  let isNotComplete = list.findIndex(item => {
    return judgeObjectComplete(item) === false
  })
  if (isNotComplete > -1) {
    return false
  } else {
    return true
  }
}