0

我创建了一些简单的代码,可以从单元格 B2 的电子表格中提取 Google Doc URL。该代码适用于某些文档,但不适用于其他文档。

该程序正确创建了文档的副本,该副本保留了所有格式。从那里开始,我的目标是用西班牙语替换英文文本。

我遇到了 Http:// 链接错误,有些文件完全重新格式化,有些则没有。

建议?

    //This function works to create a nearly perfect copy of the document from English to Spanish. Problems with URLs and some long docs.

function spanishConverter() {
  var ss = SpreadsheetApp.getActiveSpreadsheet(); //bound to Google Sheet
  var listDoc = ss.getSheetByName('Doc List'); //SpreadSheet Page 
  
  var docEng = listDoc.getRange(2,2).getValue(); //Cell pulling URL from
   
  
  var currentDoc = DocumentApp.openByUrl(docEng); //Opens the English version from URL on SpreadSheet
  var docName = currentDoc.getName(); 
  var docId = currentDoc.getId();
  
   
  var newDoc = DriveApp.getFileById(docId).makeCopy('Spanish ' + docName).getUrl(); //Opens and makes a copy and captures URL
  
  
  var newSp = DocumentApp.openByUrl(newDoc);
  
  var body = newSp.getBody();
  var paragraphs = body.getParagraphs();


  //This script loops throught the paragraphs
  for(var i=0; i<paragraphs.length; i++)
  {
    var text = paragraphs[i].getText(); //pulls text per paragraph
    var transText = LanguageApp.translate(text, 'en', 'es');
    Logger.log([text,transText]);
    if (text !== "") //skips blanks 
    {
    body.replaceText(text, transText);
    }
  }

}

4

1 回答 1

0

这是完整的解决方案。除非将 HTML 链接解释为文本元素,否则将跳过它们。

// This function works to create a nearly perfect copy of the document
// from English to Spanish.

function spanishConverter() {
  var ss = SpreadsheetApp.getActiveSpreadsheet(); //bound to Google Sheet
  var listDoc = ss.getSheetByName('Doc List'); //SpreadSheet Page 
  
  var docEng = listDoc.getRange(2,2).getValue(); //Cell pulling URL from
   
  
  var currentDoc = DocumentApp.openByUrl(docEng); //Opens the English version from URL on SpreadSheet
  var docName = currentDoc.getName(); 
  var docId = currentDoc.getId();
  
   
  var newDoc = DriveApp.getFileById(docId).makeCopy('Spanish - ' + docName).getUrl(); //Opens and makes a copy and captures URL
  
  
  var newSp = DocumentApp.openByUrl(newDoc);
  
  var body = newSp.getBody();
  var paragraphs = body.getParagraphs();


  //This script loops throught the paragraphs
  for(var i=0; i<paragraphs.length; i++)
  {
    var para = paragraphs[i];
    var text = para.getText(); //pulls text per paragraph
    var atts = para.getAttributes(); //pulls formatting attributes to set when appending text
    var transText = LanguageApp.translate(text, 'en', 'es');
    Logger.log([atts]);
    if (text !== "") //skips blanks 
    {
      para.clear();
      para.appendText('{sp}').setAttributes(atts);
      para.replaceText('{sp}', transText);   
    }
  }

}

于 2019-10-20T11:31:48.433 回答