使用GAS处理RTF文件(对gdoc进行批量操作)

时间:2019-05-05 23:20:08

标签: google-apps-script rtf

是否可以通过编程方式将RTF文件转换为gdocs,或者如果无法转换,则只需复制内容?我有数百个存储在gdrive中,所以我希望将它们转换为使其更易于操作和稍后合并。

1 个答案:

答案 0 :(得分:2)

  • 您要将RTF文件转换为Google文档。
  • 有数百个RTF文件。

如果我的理解是正确的,那么该示例脚本如何?

作为简单的转换,您可以使用高级Google服务的Drive.Files.copy({mimeType: MimeType.GOOGLE_DOCS}, fileId)脚本。但是从您的问题来看,我认为当转换许多文件时,执行时间可能超过6分钟。因此,在此示例脚本中,我使用批处理请求将文件与Drive API的files.copy方法进行了收敛。

示例脚本:

运行脚本时,请将参数设置为main()的功能。并运行main()

// Get file IDs of Microsoft Excel files in a specific folder including subfolders.
function getFileIds(folder, fileIds, q) {
  var files = folder.searchFiles(q);
  while (files.hasNext()) {
    fileIds.push(files.next().getId());
  }
  var folders = folder.getFolders();
  while (folders.hasNext()) {
    getFileIds(folders.next(), fileIds, q);
  }
  return fileIds;
}

// Convert Microsoft Docs to Google Docs
function convertToGoogleDocs(fileIds, dest, to) {
  var limit = 100;
  var split = Math.ceil(fileIds.length / limit);
  var reqs = [];
  for (var i = 0; i < split; i++) {
    var boundary = "xxxxxxxxxx";
    var payload = fileIds.splice(0, limit).reduce(function(s, e, i) {
      s += "Content-Type: application/http\r\n" +
        "Content-ID: " + i + "\r\n\r\n" +
        "POST https://www.googleapis.com/drive/v3/files/" + e + "/copy" + "\r\n" +
        "Content-Type: application/json; charset=utf-8\r\n\r\n" +
        JSON.stringify({"parents": [dest], "mimeType": to}) + "\r\n" +
        "--" + boundary + "\r\n";
      return s;
    }, "--" + boundary + "\r\n");
    var params = {
      method: "post",
      contentType: "multipart/mixed; boundary=" + boundary,
      payload: payload,
      headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
      muteHttpExceptions: true,
    };
    var req = UrlFetchApp.getRequest("https://www.googleapis.com/batch/drive/v3", params);
    reqs.push(req);
  }
  return UrlFetchApp.fetchAll(reqs);
}

// Please run this function.
function main() {
  var sourceFolderId = "###"; // Folder ID including source files. Please set this.
  var destinationFolderId = "###"; // Folder ID that the converted files are put. Please set this.

  var from = [MimeType.RTF, MimeType.MICROSOFT_WORD_LEGACY]; // Source mimeType
  var to = MimeType.GOOGLE_DOCS; // Destination mimeType
  var q = from.reduce(function(q, e, i) {return q += "mimeType='" + e + "'" + (i < from.length - 1 ? " or " : "")}, "");
  var fileIds = getFileIds(DriveApp.getFolderById(sourceFolderId), [], q);
  Logger.log(fileIds)
  var res = convertToGoogleDocs(fileIds, destinationFolderId, to);
  Logger.log(res);
}

注意:

  • 如果文件很大,则可能会发生错误。
  • 通过Drive API检索RTF文件时,有时mimeType变为application/msword。因此我同时搜索了application/rtfapplication/msword
  • 不幸的是,在当前阶段,批处理请求无法使用介质Blob。所以我使用了files.copy方法。在这种情况下,无需使用媒体Blob即可转换文件。

参考:

如果我误解了您的问题,而这不是您想要的结果,我深表歉意。