微信小程序本地读取xls文件

微信小程序本地读取xls文件: 其中用到一个js-xlsx库:https://docs.sheetjs.com/docs/demos/frontend/vue/ , 主要思路是

1. 通过  wx.chooseMessageFile 上传文件,获得一个临时地址 tempFilePath 。

(这个地址不能当作文件路径,让js-xlsx库读取,const workbook = XLSX.readFile('临时路径'); 行不通 

2.但是这个临时路径可以通过,微信api把二进制内容获取到,即:fileSystemManager.readFile() 。

3.获取到文件二进制了,可以通过js-xlsx库读取, 

const wb = XLSX.read(arrayBuffer);
const worksheet = wb.Sheets[wb.SheetNames[0]];
 

 

例子:

1.下载js-xlsx库引入到小程序里面。

 

<button  capture-bind:tap="chooseFile">upload</button>

 

chooseFile(){
    // 获取文件系统管理器
    const fileSystemManager = wx.getFileSystemManager();
 
    // 选择文件
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success(res) {
        // 获取文件路径
        const tempFilePath = res.tempFiles[0].path;
        console.log(tempFilePath);
        // 读取文件
        fileSystemManager.readFile({
          filePath: tempFilePath,
          success(readRes) {
            // 成功获取文件内容
            console.log('文件内容:', readRes.data);//文件arrayBuffer
            
            //https://docs.sheetjs.com/docs/demos/frontend/vue
            const wb = XLSX.read(readRes.data);

            const worksheet = wb.Sheets[wb.SheetNames[0]];
            const jsonData = XLSX.utils.sheet_to_json(worksheet);
            console.log(jsonData);
          },
          fail(err) {
            // 读取文件失败处理
            console.error('读取文件失败:', err);
          }
        });
      },
      fail(err) {
        // 选择文件失败处理
        console.error('选择文件失败:', err);
      }
    });

  },

 

 

结果:

 

 

 

 

 

 

 

 

百度搜索:

小程序获取本地存储文件

在微信小程序中获取本地存储文件,可以使用wx.getFileSystemManager获取文件系统管理器,然后使用readFile方法读取本地存储的文件内容。

以下是一个示例代码:

// 获取文件系统管理器
const fileSystemManager = wx.getFileSystemManager();
 
// 选择文件
wx.chooseMessageFile({
  count: 1,
  type: 'file',
  success(res) {
    // 获取文件路径
    const tempFilePath = res.tempFiles[0].path;
 
    // 读取文件
    fileSystemManager.readFile({
      filePath: tempFilePath,
      encoding: 'utf-8',
      success(readRes) {
        // 成功获取文件内容
        console.log('文件内容:', readRes.data);
      },
      fail(err) {
        // 读取文件失败处理
        console.error('读取文件失败:', err);
      }
    });
  },
  fail(err) {
    // 选择文件失败处理
    console.error('选择文件失败:', err);
  }
});

 

库:

https://docs.sheetjs.com/docs/demos/frontend/vue

 

所以思路能否,把文件小程序临时文件路径读取成 二进制数组 arraybuffer, 在交给 SheetsJS库处理 .

 

 

文件导出 : https://blog.csdn.net/qq_45173293/article/details/134647770

 

posted @ 2024-07-25 10:14  与f  阅读(1)  评论(0编辑  收藏  举报