用灵犀写JS宏,在表格里列出目录树

wils
wils Lv.4 核心创作者

Lv.4 核心创作者

今天论坛里有朋友问,如何在表格里列出指定目录的目录树

虽然知道应该用FileSystem.readdirSync递归的遍历

但自己写恐怕得薅掉不少头发,于是让灵犀写:

function walk(dir, depth = 0) {
    const out = [];
    const items = FileSystem.readdirSync(dir).map(name => {
        const full = `${dir}\\${name}`;
        return { name, full, isDir: FileSystem.stat(full).isDirectory() };
    });
    items.sort((a, b) => (b.isDir - a.isDir) || a.name.localeCompare(b.name));
    for (const { name, full, isDir } of items) {
        out.push([...Array(depth), name]);
        if (isDir) {
            out.push(...walk(full, depth + 1));
        }
    }
    return out;
}

function rr() {
    const a = walk('C:\\Users\\Administrator\\Desktop\\tt');
    const maxCols = a.reduce((m, r) => Math.max(m, r.length), 1);
    Range("A1").Resize(a.length, maxCols).Value2 = a;
}

灵犀还贴心的将,目录排序到文件的前面🎉

命令行的结果作为对比:

最后只能感慨,写的太漂亮啦

海南省
浏览 35
收藏
1
分享
1 +1
+1
全部评论