js读取文件路劲并生成xlsx

2023-12-05


const xlsx = require("node-xlsx");
const fs = require('fs');
const path = require('path');
/**
 * fileDisplay(url, callback)
 * @param url: 你即将读取的文件夹路径
 * @param callback: 回调函数
 */



// 收集所有的文件路径
const arrFileList = [];
let timer = null;
function fileRead (url, cb){
  const filePath = path.resolve(url);
  //根据文件路径读取文件,返回文件列表
  fs.readdir(filePath, (err, files) => {
    if (err) return console.error('Error:(spec)', err)
    files.forEach((filename) => {
      //获取当前文件的绝对路径
      const filedir = path.join(filePath, filename);
      // fs.stat(path)执行后,会将stats类的实例返回给其回调函数。
      fs.stat(filedir, (eror, stats) => {
        if (eror) return console.error('Error:(spec)', err);
        // 是否是文件
        const isFile = stats.isFile();
        // 是否是文件夹
        const isDir = stats.isDirectory();
        if (isFile) {
          // 这块我自己处理了多余的绝对路径,第一个 replace 是替换掉那个路径,第二个是所有满足\\的直接替换掉
          arrFileList.push(filedir.replace(__dirname, '').replace(/\\/img, '/'))
          // 最后打印的就是完整的文件路径了
          if (timer) clearTimeout(timer)
          timer = setTimeout(() => cb && cb(arrFileList), 200)
        }
        // 如果是文件夹
        if (isDir) fileDisplay(filedir, cb);
      })
    });
  });
}


// 读取文件路劲,并生成xlsx文件
fileRead('./test', (arr) => {
  // console.log(arr, '-=')
  const newArr = []
  arr.map((item) => {
    newArr.push([item])
  })
  let sheetOptions = { "!cols": [{ wch: 500 }, { wch: 50 }, { wch: 20 }] };
  //生成buffer
  let buffer = xlsx.build([{ name: "sheet1", data: newArr }], { sheetOptions });
  //导出
  fs.writeFileSync("./测试.xlsx", buffer, { flag: "w" });

})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

js读取文件路劲并生成xlsx 的相关文章

随机推荐