데이터분석가/Coding

[GAS] 스프레드시트에 공휴일 가져오기

Jeenee_Lee 2024. 5. 25. 18:46

 

구글 스프레드시트에 휴일 정보가 있으면 할 수 있는 것들이 있으면 업무일수 계산 등 활용할 수 있는 방법들이 있다.

그런데 필요한 기간이 짧으면 수작업으로 입력할 수 있으나 기간이 길거나 변동사항이 생길때마다 업데이트할 수는 없으니 구글 캘린더에서 정보를 가져오도록 구성했다.

 

Google Apps Script

MS Office의 매크로와 같은 역할로, 스프레드시트의 기능을 넘어선 다양한 기능을 구현할 수 있다.

기본적으로는 Java Script로 구성되어 있는데, 꼭 언어를 몰라도 구글링하면 안내를 다 찾아올 수 있다.

 

전체 코드

function exportCalendarToSheet() {
  // Get the calendar ID
  const calendarId = "ko.south_korea#holiday@group.v.calendar.google.com";

  // Spread sheet의 Sheet tab의 이름
  const SheetTabName = "휴일";

  // Get the start and end time for the events you want to export
  const start = new Date(2024, 0); // year, month(0 = 1월)
  const end = new Date(2026, 0);   // year, month(0 = 1월)

  // Get the calendar events
  const events = Calendar.Events.list(calendarId, {
    timeMin: start.toISOString(),
    timeMax: end.toISOString()
  });

  // Get the active sheet
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SheetTabName);
  
  // Clear the contents of the sheet
  sheet.clearContents();

  // Write the header row to the sheet
  sheet.appendRow(["Event Name", "Year", "Month", "Day", "Date Format"]);

  // Write the events to the sheet
  for (var i = 0; i < events.items.length; i++) {
    var event = events.items[i];
    var startDate = new Date(event.start.date);
    sheet.appendRow([event.summary, Utilities.formatDate(startDate, "GMT+9", "yyyy"), Utilities.formatDate(startDate, "GMT+9", "MM"), Utilities.formatDate(startDate, "GMT+9", "dd"), Utilities.formatDate(startDate, "GMT+9", "yyyy-MM-dd")]);
  }
}

 

코드 구성 설명

// Get the calendar ID
const calendarId = "ko.south_korea#holiday@group.v.calendar.google.com";

구글 캘린더에는 캘린더 ID가 있다.

해당 캘린더의 설정 > 캘린더 통합에 캘린더ID가 기재되어 있다.

대한민국 휴일 캘린더는 공통이므로 위 코드를 그대로 사용해도 된다.

// Spread sheet의 Sheet tab의 이름
const SheetTabName = "휴일";

캘린더 정보를 넣고 싶은 Spreadsheet의 시트 이름을 삽입한다.

"휴일" 시트에 정보를 넣고자 한다.

 

// Get the start and end time for the events you want to export
const start = new Date(2024, 0); // year, month(0 = 1월)
const end = new Date(2026, 0);   // year, month(0 = 1월)

2024년부터 2025년까지 삽입하고자 한다.

여기서 `Date(year, month)`로 구성되는데 유의할 점은 month에 0은 1월을 의미한다.

(0 = 1월, 1 = 2월, ... 11 = 12월)

그래서 2024년 1월 1일부터 포함하고 싶다면 Date(2024, 0)으로 지정한다.

 

// Get the calendar events
const events = Calendar.Events.list(calendarId, {
timeMin: start.toISOString(),
timeMax: end.toISOString()
});

기간에 대한 정보를 캘린더에 반영해서 가져온다.

 

// Get the active sheet
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SheetTabName);

// Clear the contents of the sheet
sheet.clearContents();

// Write the header row to the sheet
sheet.appendRow(["Event Name", "Year", "Month", "Day", "Date Format"]);

위에서 지정한 SheetTabName을 반영해 "휴일" 시트에 대해

모든 컨텐츠를 다 삭제하고

열의 제목을 삽입한다.

 

// Write the events to the sheet
for (var i = 0; i < events.items.length; i++) {
    var event = events.items[i];
    var startDate = new Date(event.start.date);
    sheet.appendRow([event.summary, Utilities.formatDate(startDate, "GMT+9", "yyyy"), Utilities.formatDate(startDate, "GMT+9", "MM"), Utilities.formatDate(startDate, "GMT+9", "dd"), Utilities.formatDate(startDate, "GMT+9", "yyyy-MM-dd")]);
}

각 이벤트(캘린더 정보)에 대해

  • event.summary : 이벤트 정보 → 여기서는 휴일명이 된다. e.g. 설날, 어린이날 등
  • event.start.date : 이벤트 시작일자
    ※ event.end.date 정보도 존재하는데, 휴일은 '종일'로 지정되어 있으므로 start.date에서 하루 지난 날짜와 같다. 여기서는 사용하지 않는다.

각 휴일의 정보를 "휴일"시트의 행 방향으로 쌓는다.

  • Utilities.formatDate(startDate, "GMT+9", "yyyy")
    "GMT+9" : 한국 시간대로 보정한다.
    "yyyy" : 4자리로 구성된 연도 정보를 가져온다.
    "MM" : 2자리로 구성된 월 정보를 가져온다.
    "dd" : 2자리로 구성된 일 정보를 가져온다.
    "yyyy-MM-dd" : 2024-01-01 형태의 날짜 형태로 가져온다. 스프레드시트 상에서 계산이 가능한 정보가 된다.

트리거 설정

위 코드를 매번 수동으로 실행하지 않고, 트리거 설정이 가능하다.

스프레드시트를 열 때, 시간 기반(매일), 그 외 주기적인 설정이 가능하다.

휴일은 자주 변경되는 정보가 아니므로 매월 1일 오전 9시에 동작하는 것으로 설정해두었다.

실행 결과

 

코드 내에 지정한 것처럼 "휴일" 시트에 정보들이 저장되어 있다.

"Date Format"이라는 컬럼에 저장되어 있는 날짜를 이용해 NETWORKDAYS와 같은 함수에도 활용할 수 있다.

여기서 참고할 점은

  • 정렬은 별도로 지정하지 않았고,
  • 14, 20행 '섣달 그믐날'과 같은 실제 휴일이 아닌 정보도 포함되어 있다는 점이다.
  • 31행 처럼 어린이날 대체공휴일 같은 정보가 같이 포함되어 있으며,
  • 명절 연휴(설날, 추석)은 당일만 포함되어 있어 3~4일 정도 되는 연휴가 모두 포함되지는 않는다.
  • 캡쳐 상에는 포함되지 않았지만 24년 4월 10일에 있었던 국회의원 선거일도 포함되어 있다.