如何在谷歌应用程序中获取谷歌文档的内容?

时间:2012-09-25 09:23:53

标签: google-apps-script

我在获取文档内容时遇到问题。我能够获取文档ID但无法获取文档的文本。 我正在使用以下代码:

function getDocuments(user){
  var scope = 'https://docs.google.com/feeds/';
  //oAuth
  user="email-id"
  var fetchArgs = googleOAuth_('docs', scope);
  var url = scope + user+'/private/full?v=3&alt=json';
  var urlFetch = UrlFetchApp.fetch(url, fetchArgs);
  var json=Utilities.jsonParse(urlFetch.getContentText())
  var entry = json.feed.entry;
  var docs = [];
  for(var i in entry){
    var tempDoc = {};
    for(var j in entry[i]){

      tempDoc.id = entry[i].id.$t.split('%3A')[1];
    }
    docs.push(tempDoc);
    //Logger.log(docs[i])
  }


  var url='https://docs.google.com/feeds/download/documents/Export?docID=?'

  var data=UrlFetchApp.fetch(url,fetchArgs).getAs('text/html').getDataAsString()
  MailApp.sendEmail("email","","",{htmlBody:data})
}

//--------------------------------------------------------------------------------------
//Google oAuth
//Used by getDocuments(user)
function googleOAuth_(name,scope) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name);
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey("consumerkey");
  oAuthConfig.setConsumerSecret(consumersecret);
  return {oAuthServiceName:name, oAuthUseToken:"always",method:"GET"};
}

它返回文件的html格式但是,无法返回文件的内容。 请尽快与我分享任何建议..

2 个答案:

答案 0 :(得分:2)

如果您希望doc是邮件的html正文,则可以使用以下代码:

    var id = 'the ID of your document'
    var bodytext = DocumentApp.openById(id).getText();//the text content of your doc (optional)
    var url = 'https://docs.google.com/feeds/';
    var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=html&format=html&id='+id,
    googleOAuth_('docs',url)).getContentText(); 


    MailApp.sendEmail(destination email, subject, bodytext, {htmlBody:doc});

和OAuth功能:

function googleOAuth_(name,scope) {
  var oAuthConfig = UrlFetchApp.addOAuthService(name);
  oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
  oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
  oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
  oAuthConfig.setConsumerKey('anonymous');
  oAuthConfig.setConsumerSecret('anonymous');
  return {oAuthServiceName:name, oAuthUseToken:"always"};
}

答案 1 :(得分:0)

到目前为止,我不知道任何可以获取文件内容的函数,您可以参考带有文件共享链接的文档。

我希望能帮到你!