react hooks 使用过程中、汇总

工具方法

  • 数组对象 相同的归类
// T为类型  js可以直接去掉
/**
   * 数组对象  相同的归为一类
   * @param data  源数据
   * @param key 需要归类的重复key
   */
  classidiedArray<T>(data: Array<T>, key: string) {
    const map = {},
      dest = [];
    for (let i = 0; i < data.length; i++) {
      const ai: T = data[i];
      if (!map[ai["key"]]) {
        dest.push({
          key: ai["key"],
          data: [ai],
        });
        map[ai["key"]] = ai;
      } else {
        for (let j = 0; j < dest.length; j++) {
          const dj = dest[j];
          if (dj["key"] == ai["key"]) {
            dj.data.push(ai);
            break;
          }
        }
      }
    }
  },
  • 导出excel
    • 下载 npm install xlsx
/**
   * 导出excel
   * @param column 表头
   * @param list 数据
   * @param title 标题
   */
  exportExcel<V, T>(column: V, list: T[], title: string) {
    const json = list.map((item: T) => {
      return Object.keys(item).reduce((list, key) => {
        const newKey = column[key] || key;
        list[newKey] = item[key];
        return list;
      }, {});
    });

    const sheet = XLSX.utils.json_to_sheet(json);

    tools.openDownloadDialog(
      tools.sheet2blob(sheet, undefined),
      `${title}.xlsx`
    );
  },

  // 打开下载
  openDownloadDialog(url: Blob, saveName: string) {
    let saveUrl = "";
    if (typeof url === "object" && url instanceof Blob) {
      // 创建 blob地址
      saveUrl = URL.createObjectURL(url);
    }

    const aLink = document.createElement("a");
    aLink.href = saveUrl;
    // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
    aLink.download = saveName || "";
    let 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);
  },

  // 转换
  sheet2blob(sheet: any, sheetName = "sheet1") {
    const workbook = {
      SheetNames: [sheetName],
      Sheets: {},
    };

    // 生成excel的配置项
    workbook.Sheets[sheetName] = sheet;

    const wopts: WritingOptions = {
      // 生成的文件类型
      bookType: "xlsx",
      // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
      type: "binary",
    };

    const wbout = XLSX.write(workbook, wopts);
    // 字符串转ArrayBuffer
    const blob = new Blob([s2ab(wbout)], {
      type: "application/octet-stream",
    });

    function s2ab(s: any) {
      const buf = new ArrayBuffer(s.length);
      const view = new Uint8Array(buf);
      for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
      return buf;
    }
    return blob;
  },
  • 使用方法

	// 表头字段转换
	const data = {
          key: "索引",
          name: "姓名",
          age: "年龄",
          address: "地址",
        };
    // 数据
   const dataSource = [
    {
      key: "1",
      name: "胡彦斌",
      age: 32,
      address: "西湖区湖底公园1号",
    },
    {
      key: "2",
      name: "胡彦祖",
      age: 42,
      address: "西湖区湖底公园1号",
    },
  ];
  exportExcel(data, dataSource, "测试文件");
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页