从word文档转换为本机google doc

时间:2017-01-15 20:29:44

标签: google-apps-script google-drive-api

所以我可以用c#生成大约2000个单词文档,但是,我需要将它们上传到谷歌文档,采用原生谷歌文档格式。

我查看This guide尝试转换它们,但是,代码在倒数第二行失败。

(我的代码如下)

function myFunction() {
  var folder = DriveApp.getFoldersByName("test").next();
  var contents = folder.getFiles();
  while (contents.hasNext()){
    var file = contents.next();
    var fileName = file.getName();
    var officeFile = DriveApp.getFilesByName(fileName).next();
    // Use the Advanced Drive API to upload the Excel file to Drive
    // convert = true will convert the file to the corresponding Google Docs format
    var uploadFile = JSON.parse(UrlFetchApp.fetch(
      "https://www.googleapis.com/upload/drive/v2/files?uploadType=media&convert=true", 
      {
        method: "POST",
        contentType: officeFile.getMimeType(),
        payload: officeFile.getBlob().getBytes(),
        headers: {
          "Authorization" : "Bearer " + ScriptApp.getOAuthToken()
        },
        muteHttpExceptions: true
      }
    ).getContentText());


    // Remove the file extension from the original file name
    var fileName2 = officeFile.getName();
    fileName2 = fileName2.substr(0, fileName2.lastIndexOf("."));


    // Update the name of the Google Sheet created from the Excel sheet
    DriveApp.getFileById(uploadFile.getID()).setName(fileName2);  // FAILS HERE

    //Logger.log(uploadFile.alternateLink);  
  }}

TypeError:无法在对象[object Object]中找到函数getID。 (第33行,文件“代码”)

我理解这是什么类型的错误,但是,我不一定知道如何解决它。

1 个答案:

答案 0 :(得分:1)

您不需要任何UrlFetchApp操作。 Advanced Drive Service提供转化作为copy方法的一部分。需要两行代码:

  var fileId = 'ID_of_Word_file';
  Drive.Files.copy({}, fileId, {'convert': true});

您需要在scropt菜单中启用此服务:请参阅参考资料>高级服务。

如果遍历文件夹,请使用.next()从文件迭代器获取每个文件,并使用getId()获取其ID;按上述步骤进行。

第一个参数中的空对象可用于命名新文件:例如,它可以是{'title': 'Name of new file'}

相关问题