본문 바로가기
GAS

[GAS] sheets데이터를 html 문서를 작성해보자

by 일등미노왕국 2023. 4. 19.

https://www.youtube.com/watch?v=K6lRjCrdqis&t=1003s 

 

오늘은 sheets에 있는 데이터를 html 문서화 하는 코드를 작성해보려고 한다.

 

나중에 웹앱을 시트에 있는 데이터를 통해 구성하려고 하면 시트에 있는 내용을 템플릿화해서 html 코드에 입혀주는 작업을 해야 하는데 오늘은 그 작업의 초기 단계라고 보면 된다.

 

sales.html을 열어보면

태그 사이사이에 <?!= 키워드 ?> 이런 것들이 있을 것이다. 

이것은 gs에서 템플릿화하여서 키워드에 치환되게 된다.

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <title><?!= t_title ?></title>
  </head>
  <body>
    <table>
      <thead><?!= t_head ?></thead>
      <tbody><?!= t_body ?></tbody>
    </table>
    
  </body>
</html>


이 사이에 들어가는 [치환]에 앱스스크립트의 내용이 템플릿트.evauate() 명령어로 html에 들어가게 된다.

 

https://yeoncoding.tistory.com/46

 

[javascript] join() 함수 - 배열의 원소를 문자열로 합치기

Array.join() join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만든다. 문법 arr.join([separator]) separator는 매개변수로, 배열의 각 요소를 구분할 문자열이다. 이 구분자는 필요한 경우 문자

yeoncoding.tistory.com

이분이 정리한 Join 함수에 대해서 알아보면 아래와 같다.

https://yeoncoding.tistory.com/46

 

더보기
function to_html() {

  
  let tmp = HtmlService.createTemplateFromFile('Sales'),                  // 템플릿을 tmp 선언

      sht = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0],         // 처음시트를 sht로 선언

      values = sht.getRange("a2").getDataRegion().getDisplayValues(),     // [a2]부터 연결된 보이는 값들을 Values 로 선언

      head = values.shift();                                              // values에서 가장 처음 배열의 값을 잘라서 head로 선언
  
      tmp.t_title = 'Sales Report'                                        // 템플릿(html) t_title 의 치환값
      tmp.t_head = "<tr><th>" + head.join("</th><th>") + "</th></tr>"     // 템플릿(html) t_head 의 치환값
      tmp.t_body = values.map(function(row){

        return "<tr><td>" + row.join("</td><td>") + "</td></tr>"          // 템플릿(html) t_body 의 치환값 

      }).join("\n")

      sht.getRange("f2").clearContent();                                  // 기존값 제거
      sht.getRange("f2").setValue(tmp.evaluate().getContent() );          // [f2] 영역에 출력

  
   
}

여기서 어려워 보이는 코드가

tmp.t_title = 'Sales Report'                                      
      tmp.t_head = "<tr><th>" + head.join("</th><th>") + "</th></tr>" 
      tmp.t_body = values.map(function(row){

        return "<tr><td>" + row.join("</td><td>") + "</td></tr>"      

      }).join("\n")

 

이 부분일텐데..

결과값인 아래의 태그 조합을 보게 되면 join 함수의 사용법에 대해서 알 수 있을 것이다.

tmp.t_body = values.map(function(row){

        return "<tr><td>" + row.join("</td><td>") + "</td></tr>"          // 템플릿(html) t_body 의 치환값 

      }).join("\n")

t_body  만 더 구체적으로 설명하면 values의 배열값을 map 함수로 변형을 할건데 그 요소로 사용될 녀석이 row 라는 녀석이다. 이 row라는 녀석은 배열의 형태를 갖으므로 1차원 배열로 조합을 한 후 다시 이 배열을 개행문자를 조합하여 2차원 배열로 바꿔주는 구문이다.

 

실행을 하면

이런식으로 스프레드시트의 표의 데이터를 html 문법으로 변경할 수 있다.

추후 홈페이지나 웹앱의 데이터로 사용할 수도 있기 때문에 익히기를 바란다.

https://docs.google.com/spreadsheets/d/15GoCnTFAVTM5RftyxWAl0RVyiWOa3QtrRCWbaRwxdZo/edit?usp=sharing

댓글