LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Thursday, May 2, 2019

HtmlServiceのテキストエリアからGoogleドキュメントに書き込みたい


この記事でやること

GoogleドキュメントのテキストをHtmlServiceのテキストエリアに読み込みたい
でテキストエリアに読み込んだあとで

編集したテキストをドキュメントに反映させるところまで行きます。



コード.gs
function doGet(e) {
  return HtmlService.createHtmlOutputFromFile("index");
}

var docUrl = 'https://docs.google.com/document/d/ID/edit';
var docId = docUrl.split('/d/')[1].split('/')[0];

function getDocText() {
  var doc = DocumentApp.openById(docId);
  var body = doc.getBody().getText();
  return body;
}

function updateDocText(text) {
  var doc = DocumentApp.openById(docId);
  var body = doc.getBody();
  body.setText(text);
}




index.html
<!DOCTYPE html>
<html>
<body>
  <textarea id="ta" style="width: 20vw;height:90vh;"></textarea>
<script>
getData();

/************************************
elem(id)
************************************/
function elem(id) {
  return document.getElementById(id);
}

/************************************
getData()
************************************/
function getData() {
  google.script.run
  .withFailureHandler(onFailure)
  .withSuccessHandler(gotDocText)
  .getDocText();
}

/************************************
gotDocText(result)
************************************/
function gotDocText(result) {
  elem('ta').value = result;
}

/************************************
updateData()
************************************/
function updateData() {
  var text = elem('ta').value;
  google.script.run
  .withFailureHandler(onFailure)
  .updateDocText(text);
}


/************************************
onFailure(e)
************************************/
function onFailure(e) {
  alert([e.message, e.stack]);
}

/************************************
timeout
2秒後にupdateData()を実行する
************************************/
var timeOut;
var milisec = 2000;

document.addEventListener("load", timeoutStart);
document.addEventListener("click", resetTimeout);
document.addEventListener("mousemove", resetTimeout);
document.addEventListener("keypress", resetTimeout);

function timeoutStart(){
  timeOut = setTimeout('updateData()', milisec);
}

function resetTimeout() {
  clearTimeout(timeOut);
  timeoutStart();
}

</script>
</body>
</html>



Latest post

Extracting data from Google Sheets with regular expressions

Introduction Regular expressions are a powerful tool that can be used to extract data from text.  In Google Sheets, regular expressions ca...