Code này sẽ lấy cây thư mục của folder trên google và dường dẫn của từng thư mục lưu về file google sheet của tài khoản..
1. Truy cập https://script.google.com/
2. Tạo project và dán code bên dưới vào. Nhớ đổi tên thư mục cần lấy. Sau đó Save -> Run (cấp quyền nếu chạy lần đầu).
function exportFolderTreeToSheet() {
const folderId = '1vPZRs1DOwzuvkzo0ErYc9PgOu5dwxEvy'; // Thay bằng ID thư mục gốc
const rootFolder = DriveApp.getFolderById(folderId);
const folderList = [];
/**
* Hàm đệ quy để lấy thư mục con và hiển thị dạng cây.
* @param {Folder} folder - Thư mục hiện tại.
* @param {number} level - Cấp độ thư mục (0 là gốc).
*/
function getSubfolders(folder, level) {
const indent = "─".repeat(level); // Hiển thị cây với dấu "─"
const folderName = `${indent} ${folder.getName()}`;
const folderPath = getFullPath(folder);
const folderUrl = folder.getUrl();
folderList.push([folderName.trim(), folderPath, folderUrl]);
const subfolders = folder.getFolders();
while (subfolders.hasNext()) {
getSubfolders(subfolders.next(), level + 1); // Đệ quy cho thư mục con
}
}
/**
* Hàm lấy đường dẫn đầy đủ của thư mục.
* @param {Folder} folder - Thư mục cần lấy đường dẫn.
* @returns {string} - Đường dẫn đầy đủ.
*/
function getFullPath(folder) {
let path = folder.getName();
let parent = folder.getParents();
while (parent.hasNext()) {
const p = parent.next();
path = `${p.getName()}/${path}`;
parent = p.getParents();
}
return path;
}
// 📂 Bắt đầu từ thư mục gốc
getSubfolders(rootFolder, 0);
if (folderList.length === 0) {
Logger.log("🚫 Không tìm thấy thư mục con.");
return;
}
// 📄 Tạo Google Sheet mới
const sheet = SpreadsheetApp.create(`Cây thư mục - ${rootFolder.getName()}`);
const sheetTab = sheet.getActiveSheet();
// 📝 Thêm tiêu đề
const headers = ["🌳 Tên thư mục (cây)", "📁 Đường dẫn đầy đủ", "🔗 Link truy cập"];
sheetTab.appendRow(headers);
// 📥 Xuất dữ liệu ra Sheet
sheetTab.getRange(2, 1, folderList.length, 3).setValues(folderList);
// 🎨 Định dạng cột
sheetTab.autoResizeColumns(1, 3);
Logger.log(`✅ Đã xuất ${folderList.length} thư mục ra Google Sheets: ${sheet.getUrl()}`);
}
0 Comments