首页 > 其他分享 >原生js导出word、导出excel

原生js导出word、导出excel

时间:2022-10-18 14:22:12浏览次数:88  
标签:return url 导出 excel fileName link str word const

导出word文件

导出部分HTML成word文件。

注意:部分样式word不支持,图片需要设置width和height属性

/**
 * 下载文件
 * @param {string} url 文件地址
 * @param {string} fileName 文件名,含后缀
 */
const download = (url, fileName) => {
    try {
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        return true;
    } catch (err) {
        return false;
    }
};

/**
 * 导出word
 * @param {string | HTMLElement} domOrSelector 选择器或者DOM元素
 * @param {string} fileName 文件名,不含后缀
 * @param {string} style 样式
 */
const exportWord = (domOrSelector, fileName = "word", style = "") => {
    if (!domOrSelector) {
        return Promise.reject("缺少导出元素或者导出元素选择器");
    }

    const dom =
        typeof domOrSelector === "string"
        ? document.querySelector(domOrSelector)
        : domOrSelector;

    if (!dom) {
        return Promise.reject("未获取到元素选择器对应的元素");
    }

    const exportHtml = `
        <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">
            <head>
                <meta charset='utf-8'>
                <title>${fileName}</title>
                ${style ? `<style>${style}</style>` : ""}
            </head>
            <body>
                ${dom.outerHTML}
            </body>
        </html>
    `;

    const url =
        "data:application/vnd.ms-word;charset=utf-8," +
        encodeURIComponent(exportHtml);

    download(url, fileName + ".doc");

    return Promise.resolve(true);
};

导出Excel文件

导出json数据成excel

columns配置项形如: [{ title: '姓名', field: 'name', }, { title: '个人主页', render: (_, item, index) => `<a href="${item.blog}">${item.blog}</a>` } ]

一般情况下,只需要指定标题title和字段名field。有些字段需要一些逻辑处理,可以用render(value, item, index)来处理。

      /**
       * 下载文件
       * @param {string} url 文件地址
       * @param {string} fileName 文件名,含后缀
       */
      const download = (url, fileName) => {
        try {
          let link = document.createElement("a");
          link.style.display = "none";
          link.href = url;
          link.setAttribute("download", fileName);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          return true;
        } catch (err) {
          return false;
        }
      };

      const base64 = (str) => window.btoa(unescape(encodeURIComponent(str)));

      const isNull = (value) => [undefined, null].includes(value);

      const displayData = (data) => {
        if (data === null) {
          return "";
        }
        if (typeof data !== "object") {
          if (isNull(data)) {
            return "";
          }
          return data;
        }
        return data.toString();
      };

      const exportExcel = (
        tableData,
        columns,
        fileName = new Date().toDateString(),
        sheetName = "Sheet1"
      ) => {
        try {
          let str = "";
          // 表头
          str += "<tr>";
          columns.forEach((column) => {
            const { title, titleRender } = column;
            if (titleRender) {
              str += `<th>${displayData(titleRender(index))}</th>`;
            } else {
              str += `<th>${displayData(title)}</th>`;
            }
          });
          str += "</tr>";
          tableData?.forEach((item, index) => {
            // 内容
            str += "<tr>";
            columns.forEach((column) => {
              const { field, render } = column;
              if (render) {
                str += `<td>${displayData(
                  render(item[field], item, index)
                )}</td>`;
              } else {
                str += `<td>${displayData(item[field])}</td>`;
              }
            });
            str += "</tr>";
          });

          console.log(str);

          // 下载的表格模板数据
          const template = `
            <html xmlns:o="urn:schemas-microsoft-com:office:office" 
                    xmlns:x="urn:schemas-microsoft-com:office:excel" 
                    xmlns="http://www.w3.org/TR/REC-html40">
                <head>
                <!--[if gte mso 9]>
                    <xml>
                        <x:ExcelWorkbook>
                            <x:ExcelWorksheets>
                                <x:ExcelWorksheet>
                                    <x:Name>${sheetName}</x:Name>
                                    <x:WorksheetOptions>
                                        <x:DisplayGridlines/>
                                    </x:WorksheetOptions>
                                </x:ExcelWorksheet>
                            </x:ExcelWorksheets>
                        </x:ExcelWorkbook>
                    </xml>
                <![endif]-->
                </head>
                <body>
                <table>${str}</table>
                </body>
            </html>`;

          const uri = "data:application/vnd.ms-excel;base64,";
          const url = uri + base64(template);
          download(url, fileName + ".xlsx");

          return Promise.resolve(true);
        } catch (err) {
          return Promise.reject(err);
        }
      };

使用例子(测试导出excel的代码)

      const tableData = [
        {
          name: "张三",
          email: "[email protected]",
          age: 18,
          home: "https://www.baidu.com",
        },
        {
          name: "李四",
          email: "[email protected]",
          age: 18,
          home: "https://www.baidu.com",
        },
        {
          name: "王五",
          email: "[email protected]",
          age: 18,
          home: "https://www.baidu.com",
        },
        {
          name: "赵六",
          email: "[email protected]",
          age: 18,
          home: "https://www.baidu.com",
        },
      ];

      const columns = [
        { title: "姓名", field: "name" },
        {
          title: "邮箱",
          field: "email",
          render: (email, record) =>
            `<a href="mailto:${record.email}">${email}</a>`,
        },
        { title: "年龄", field: "age" },
        {
          title: "个人主页",
          field: "home",
          render(home, record) {
            return `<a href="${home}">${record.name}的网站</a>`;
          },
        },
      ];

      exportExcel(tableData, columns, "test", "sheet name");

 

标签:return,url,导出,excel,fileName,link,str,word,const
From: https://www.cnblogs.com/zhaodesheng/p/16802294.html

相关文章