将特定文件夹中找到的所有文档的正文复制到Google电子表格中

时间:2016-02-29 23:05:22

标签: google-apps-script google-sheets google-docs

我正在尝试创建一个脚本,该脚本可获取Google云端硬盘文件夹中的所有(Google Doc)文档ID,从每个文档中抓取正文,并将其返回到this spreadsheet中的行。

以下语法可以获取文件ID和名称,但不会抓取正文:

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ui = SpreadsheetApp.getUi().createAddonMenu();  
  ui.addItem('List all body components of files inside a folder without including subfolders', 'list_all_body_components_of_files_inside_one_folder_without_subfolders')     
      .addToUi();
}

function list_all_body_components_of_files_inside_one_folder_without_subfolders() {
  var sh = SpreadsheetApp.getActiveSheet();

 // Prompt the user for a google drive folder ID
  var folderID = Browser.inputBox("Enter the folder ID to search in - It's the bit in the URL after /folders/:");

// return the folder identified by that ID number for further manipulation
  var folder = DriveApp.getFolderById(folderID); 

// print the list to columns A through C 
var list = [];
  list.push(['Body','Name','ID']);
  var files = folder.getFiles();
  while (files.hasNext()){
    file = files.next();
    var row = []
    row.push(file.getBlob(),file.getName(),file.getId())
    list.push(row);
  }
  sh.getRange(1,1,list.length,list[0].length).setValues(list);
}

我认为问题出在file.getBlob我已经尝试过了 file.getBlob.getDataAsString(),但返回:

  

TypeError:在对象函数getBlob(){/ * * /}中找不到函数getDataAsString。

如何检索每个文档正文的文本

1 个答案:

答案 0 :(得分:1)

由于我们感兴趣的是Google文档,请将文件扫描重点放在:

var files = folder.getFilesByType(MimeType.GOOGLE_DOCS);

然后在处理文件迭代器时,使用文档ID和DocumentApp将文件作为Google文档打开 - 这样,可以随时访问正文。

更新的代码:

function list_all_body_components_of_files_inside_one_folder_without_subfolders() {
  var sh = SpreadsheetApp.getActiveSheet();

 // Prompt the user for a google drive folder ID
  var folderID = Browser.inputBox("Enter the folder ID to search in - It's the bit in the URL after /folders/:");

// return the folder identified by that ID number for further manipulation
  var folder = DriveApp.getFolderById(folderID); 

// print the list to columns A through C 
var list = [];
  list.push(['Body','Name','ID']);
  var files = folder.getFilesByType(MimeType.GOOGLE_DOCS);
  while (files.hasNext()){
    var fileId = files.next().getId();
    var doc = DocumentApp.openById(fileId);
    var row = []
    row.push(doc.getBody().editAsText().getText(),
             doc.getName(),
             fileId)
    list.push(row);
  }
  sh.getRange(1,1,list.length,list[0].length).setValues(list);
}