uniapp实现安卓端导出execl、打包excel为zip压缩文件、分享zip压缩文件到微信、qq

导出excel

学习自 https://www.cnblogs.com/nanyang520/p/13474603.html

使用uniapp的h5+ api(JS API调用手机的原生能力)调用安卓功能,文档可见https://www.html5plus.org/doc/zh_cn/zip.html
直接在vue文件中使用相应api即可,无需导入,uniapp默认支持,编译到安卓真机上进行调试

原理在于生成excel字符串,写入文件中,这种方式可能存在一定兼容性问题,有的excel软件或版本可能打不开

  tableToExcel() {
      // 要导出的json数据
      const jsonData = [{
        name: '测试数据',
        phone: '123456',
        email: '123@456.com'
      }
      ]
      // 列标题
      let worksheet = 'sheet1'
      let str = '<tr><td>姓名</td><td>电话</td><td>邮箱</td></tr>'
      // 循环遍历,每行加入tr标签,每个单元格加td标签
      for (let i = 0; i < jsonData.length; i++) {
        str += '<tr>'
        for (let item in jsonData[i]) {
          // 增加\t为了不让表格显示科学计数法或者其他格式
          str += `<td>${jsonData[i][item] + '\t'}</td>`
        }
        str += '</tr>'
      }
      // 下载的表格模板数据
      let template = `<html
                 xmlns:v="urn:schemas-microsoft-com:vml"
                 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>
                  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                <!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
                <x:Name>${worksheet}</x:Name>
                <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
                </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
                <style type="text/css">
                 .text {
                       text-align: center;
                     }
                </style>
                </head>
                <body><table>${str}</table></body>
                </html>`;
      // 下载模板
      this.exportFile(template);
    },
    exportFile(fileData, documentName = "项目Excel文件") {
      plus.io.requestFileSystem(plus.io.PUBLIC_DOCUMENTS, (fs) => {
        let rootObj = fs.root;
        let fullPath = rootObj.fullPath;
        console.log(
          "开始导出数据********",
          documentName,
          plus.io.PUBLIC_DOCUMENTS,
          fullPath
        );
        // 创建文件夹
        rootObj.getDirectory(documentName, { create: true }, (dirEntry) => {
          // 获取当前的年月继续创建文件夹
          let date = new Date();
          let year = date.getFullYear();
          let month = date.getMonth() + 1;

          dirEntry.getDirectory(
            `${year}年${month}月`,
            { create: true },
            (dirEntry2) => {
              // 创建文件,防止重名
              let fileName = "excel";
              dirEntry2.getFile(
                `${fileName}.xlsx`,
                { create: true },
                (fileEntry) => {
                  fileEntry.createWriter((writer) => {
                    writer.onwrite = (e) => {
                      // 导出路径
                      this.excelDirPath = `${fullPath}/${documentName}/${year}年${month}月`;
                      uni.showToast({
                        title: `成功导出`,
                        icon: "success",
                      });
                    };
                    writer.write(fileData); // 写入内容
                  });
                }
              );
            }
          );
        });
      });
    },

打包文件夹为zip压缩文件

  compress() {
    // excel文件所在文件夹
    const path = this.excelDirPath + "/";
    // 打包需要系统的绝对路径
    const targetPath = plus.io.convertAbsoluteFileSystem(path);
    // 文件夹打包后的系统绝对路径
    const zipfile = plus.io.convertAbsoluteFileSystem(
        "/storage/emulated/0" + this.excelDirPath + ".zip"
      );
    // 调用压缩文件夹api
    plus.zip.compress(
        targetPath,
        zipfile,
        function () {
          console.log(
            "Compress success!",
            plus.io.convertLocalFileSystemURL(zipfile)
          );
        },
        function (error) {
          console.log("Compress error!", error);
        }
      );
   }

分享zip压缩文件到微信、qq等

使用市场插件life-FileSharehttps://ext.dcloud.net.cn/plugin?id=2307

下载插件,在manifest.json—>App原生插件配置 勾选life-FileShare

导入插件

<script>
const FileShare = uni.requireNativePlugin("life-FileShare");
export default {
  ...

使用插件,该插件是原生插件,会调用手机系统的分享弹窗,如果手机上安装了微信、qq等应用,则会在弹窗中显示相应应用,如果指定"QQ",则分享弹窗中只有"QQ"图标

  // 调用压缩文件夹api
    plus.zip.compress(
        targetPath,
        zipfile,
        function () {
          console.log(
            "Compress success!",
            plus.io.convertLocalFileSystemURL(zipfile)
          );
          // 分享文件
          FileShare.render({
            type: "SYSTEM",
            // QQ为QQ,微信为WX,系统默认是SYSTEM,不填写默认SYSTEM
            // type:"QQ", 
            filePath: plus.io.convertLocalFileSystemURL(zipfile),
          });
        },
        function (error) {
          console.log("Compress error!", error);
        }
      );
   }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值