GCP/Apps Script

Apps Script로 Google Sheets에서 Date 정보 가공하기

whistory 2022. 9. 16. 15:54
반응형

 

 

Google Sheets에서 날짜에 대한 정보를 가져오길 원한다.

 

 

=IF(ISBLANK(A4), "", YEAR(A4)&" 년")

=IF(ISBLANK(A4), "", MONTH(A4)&" 월")

=IF(ISBLANK(A4), "", DAY(A4)&" 일")

=IF(ISBLANK(A4), "", WEEKNUM(A4)&" 주차")

=IF(ISBLANK(A4), "", TEXT(WEEKDAY(A4), "ddd"))

 

 

 

만약 BigQuery에서 데이터를 가져와서, 수식을 할당하려면?

const sheet         = SpreadsheetApp.openByUrl(sheetUrl).getSheetByName(sheetName);
const sheet_lastrow = sheet.getLastRow();

// 월 수식 할당
const planYearCell       = sheet.getRange("B4:B"+sheet_lastrow);
const planYearCondition  = "R[0]C[-1]";
planYearCell.setFormula('=IF(ISBLANK('+planYearCondition+'), "", YEAR('+planYearCondition+')&" 년")');

// 월 수식 할당
const planMonthCell       = sheet.getRange("C4:C"+sheet_lastrow);
const planMonthCondition  = "R[0]C[-2]";
planMonthCell.setFormula('=IF(ISBLANK('+planMonthCondition+'), "", MONTH('+planMonthCondition+')&" 월")');

// 월 수식 할당
const planMonthCell       = sheet.getRange("D4:D"+sheet_lastrow);
const planMonthCondition  = "R[0]C[-3]";
planMonthCell.setFormula('=IF(ISBLANK('+planMonthCondition+'), "", DAY('+planMonthCondition+')&" 일")');

// 주차 수식 할당
const planWeekNumCell       = sheet.getRange("E4:E"+sheet_lastrow);
const planWeekNumCondition  = "R[0]C[-4]";
planWeekNumCell.setFormula('=IF(ISBLANK('+planWeekNumCondition+'), "", WEEKNUM('+planWeekNumCondition+')&" 주차")');

// 요일 수식 할당
const planDayCell       = sheet.getRange("F4:F"+sheet_lastrow);
const planDayCondition  = "R[0]C[-5]";
const palnDayText       = 'TEXT(WEEKDAY('+planDayCondition+'), "ddd")';
planDayCell.setFormula('=IF(ISBLANK('+planDayCondition+'), "", ' + palnDayText + ')');

 

 

※ 9/22 추가

setFormula 를 쓰니까

B, C, D 컬럼에 한줄 씩 값이 저장되는게 보여서 느려보인다.

setFormulas 를 이용해 지정된 영역에 한번에 값을 할당한다.

const lastRow = sheet.getLastRow();
const rowCount = parseInt(lastRow) - 8;

// 월 수식 할당
const planMonthCondition  = "R[0]C[-1]";
// 주차 수식 할당
const planWeekNumCondition  = "R[0]C[-2]";
// 요일 수식 할당
const planDayCondition  = "R[0]C[-3]";
const palnDayText       = 'TEXT(WEEKDAY('+planDayCondition+'), "ddd")';

const dateCell     = sheet.getRange("B9:D"+lastRow);
const dateFormula1 = '=IF(ISBLANK('+planMonthCondition+'), "", MONTH('+planMonthCondition+')&" 월")';
const dateFormula2 = '=IF(ISBLANK('+planWeekNumCondition+'), "", WEEKNUM('+planWeekNumCondition+')&" 주차")';
const dateFormula3 = '=IF(ISBLANK('+planDayCondition+'), "", ' + palnDayText + ')';

const dateItems = [dateFormula1, dateFormula2, dateFormula3];
const dateFormulas = Array.apply(null, Array(rowCount)).map(_ => dateItems);
dateCell.setFormulas(dateFormulas);

 

 

반응형