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);
        }
      );
   }
  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java 实现 Excel 文件导出可以使用 Apache POI 库,该库提供了丰富的 API 用于读取、写入和操作 Excel 文件。下面是一个简单的 Java 代码示例,演示如何使用 Apache POI 将数据导出Excel 文件: ```java import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelExporter { public static void main(String[] args) throws IOException { // 创建工作簿 XSSFWorkbook workbook = new XSSFWorkbook(); // 创建工作表 Sheet sheet = workbook.createSheet("Sheet1"); // 创建标题行 Row headerRow = sheet.createRow(0); String[] headers = {"ID", "Name", "Age"}; for (int i = 0; i < headers.length; i++) { Cell cell = headerRow.createCell(i); cell.setCellValue(headers[i]); } // 创建数据行 List<User> users = getUsers(); for (int i = 0; i < users.size(); i++) { User user = users.get(i); Row dataRow = sheet.createRow(i + 1); dataRow.createCell(0).setCellValue(user.getId()); dataRow.createCell(1).setCellValue(user.getName()); dataRow.createCell(2).setCellValue(user.getAge()); } // 导出文件 FileOutputStream outputStream = new FileOutputStream("users.xlsx"); workbook.write(outputStream); workbook.close(); outputStream.close(); System.out.println("Excel 文件导出完成!"); } // 模拟获取用户数据 private static List<User> getUsers() { List<User> users = new ArrayList<>(); users.add(new User(1, "张三", 20)); users.add(new User(2, "李四", 22)); users.add(new User(3, "王五", 25)); return users; } } class User { private int id; private String name; private int age; public User(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 上述代码使用 XSSFWorkbook 创建了一个工作簿,然后创建了一个名为“Sheet1”的工作表。接下来,创建了标题行和数据行,向数据行中填充数据。最后,将数据导出到名为“users.xlsx”的 Excel 文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值