JavaScript
// ── 계리 커스텀 함수 정의 (내보낸 파일을 다시 열 때도 동일하게 등록되어 있어야 재계산됨) ──
function MortalityRate() { this.name = 'MORTALITY'; this.minArgs = 1; this.maxArgs = 1; }
MortalityRate.prototype = new GC.Spread.CalcEngine.Functions.Function();
MortalityRate.prototype.evaluate = function(age) {
const table = {
30:0.00082, 31:0.00089, 32:0.00097, 33:0.00106, 34:0.00117,
35:0.00130, 36:0.00145, 37:0.00163, 38:0.00184, 39:0.00209,
40:0.00238, 41:0.00271, 42:0.00309, 43:0.00352, 44:0.00401,
45:0.00456, 46:0.00518, 47:0.00588, 48:0.00667, 49:0.00756
};
return table[Math.floor(age)] || 0.001;
};
function SurvivalRate() { this.name = 'SURVIVAL'; this.minArgs = 2; this.maxArgs = 2; }
SurvivalRate.prototype = new GC.Spread.CalcEngine.Functions.Function();
SurvivalRate.prototype.evaluate = function(age, n) {
let px = 1;
for (let t = 0; t < n; t++) px *= (1 - MortalityRate.prototype.evaluate(age + t));
return px;
};
function AnnuityPV() { this.name = 'ANNUITYPV'; this.minArgs = 3; this.maxArgs = 3; }
AnnuityPV.prototype = new GC.Spread.CalcEngine.Functions.Function();
AnnuityPV.prototype.evaluate = function(age, n, i) {
let pv = 0;
const v = 1 / (1 + i);
for (let t = 0; t < n; t++) pv += Math.pow(v, t) * SurvivalRate.prototype.evaluate(age, t);
return pv;
};
// ── 계리 함수가 이미 반영된 Excel 리포트 형태로 초기 구성 ──
const spread = new GC.Spread.Sheets.Workbook(document.getElementById('spreadContainer'));
spread.addCustomFunction(new MortalityRate());
spread.addCustomFunction(new SurvivalRate());
spread.addCustomFunction(new AnnuityPV());
const sheet = spread.getActiveSheet();
sheet.name('계리 리포트');
spread.suspendPaint();
sheet.setColumnWidth(0, 220);
sheet.setColumnWidth(1, 140);
sheet.setColumnWidth(2, 70);
sheet.addSpan(0, 0, 1, 3);
sheet.setValue(0, 0, '계리 리포트 (Excel 가져오기·내보내기)');
sheet.getCell(0, 0).font('bold 15px sans-serif').backColor('#1565C0').foreColor('#fff')
.hAlign(GC.Spread.Sheets.HorizontalAlign.center).vAlign(GC.Spread.Sheets.VerticalAlign.center);
sheet.setRowHeight(0, 40);
sheet.addSpan(2, 0, 1, 3);
sheet.setValue(2, 0, '▶ 입력값');
sheet.getCell(2, 0).backColor('#37474F').foreColor('#fff').font('bold 12px sans-serif');
sheet.setRowHeight(2, 28);
const inputRows = [
['피보험자 나이', 40, '세'],
['보험 기간', 10, '년'],
['예정 이율', 3, '%'],
];
inputRows.forEach(([label, val, unit], i) => {
const r = 3 + i;
sheet.setValue(r, 0, label);
sheet.setValue(r, 1, val);
sheet.setValue(r, 2, unit);
sheet.getCell(r, 0).backColor('#ECEFF1');
sheet.getCell(r, 1).backColor('#ECEFF1').hAlign(GC.Spread.Sheets.HorizontalAlign.center).font('bold 12px sans-serif');
sheet.setRowHeight(r, 26);
});
sheet.addSpan(7, 0, 1, 3);
sheet.setValue(7, 0, '▶ 계리 함수 산출 결과 (수식 그대로 저장)');
sheet.getCell(7, 0).backColor('#E65100').foreColor('#fff').font('bold 12px sans-serif');
sheet.setRowHeight(7, 28);
const formulaRows = [
['위험률 =MORTALITY(B4)', '=MORTALITY(B4)'],
['생존율 =SURVIVAL(B4,B5)', '=SURVIVAL(B4,B5)'],
['연금현가 =ANNUITYPV(B4,B5,B6/100)', '=ANNUITYPV(B4,B5,B6/100)'],
];
formulaRows.forEach(([label, formula], i) => {
const r = 8 + i;
sheet.setValue(r, 0, label);
sheet.setFormula(r, 1, formula);
sheet.addSpan(r, 1, 1, 2);
sheet.getCell(r, 0).backColor('#FFF3E0').font('11px sans-serif');
sheet.getCell(r, 1).backColor('#FFF3E0')
.hAlign(GC.Spread.Sheets.HorizontalAlign.right)
.font('bold 12px sans-serif').foreColor('#E65100');
sheet.setRowHeight(r, 26);
});
spread.resumePaint();
// 공통: xlsx blob을 CodePen 샌드박스에서도 동작하는 data URI 방식으로 다운로드
function downloadXlsxBlob(blob, filename, status, successMsg) {
const reader = new FileReader();
reader.onload = function() {
const a = document.createElement('a');
a.href = reader.result;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
if (status) status.textContent = successMsg;
};
reader.readAsDataURL(blob);
}
// ── Excel 내보내기(수식포함): 수식 텍스트(=MORTALITY(B4) 등)는 저장되지만 함수의 JS 구현은 파일에 포함되지 않는다 ──
document.getElementById('btnExportFormula')?.addEventListener('click', function() {
const status = document.getElementById('importStatus');
if (status) status.textContent = '내보내는 중...';
spread.export(function(blob) {
downloadXlsxBlob(blob, '계리_리포트_수식포함.xlsx', status, '✅ 내보내기 완료 — 계리 함수 수식 포함 (함수 구성이 파일에 노출됨)');
}, function(e) {
console.error(e);
if (status) status.textContent = '❌ 내보내기 실패';
}, {
fileType: GC.Spread.Sheets.FileType.excel
});
});
// ── Excel 내보내기(값만): includeFormulas:false로 수식을 완전히 제거하고 계산된 값만 저장 — 계리 모델 로직 보호 ──
document.getElementById('btnExportValues')?.addEventListener('click', function() {
const status = document.getElementById('importStatus');
if (status) status.textContent = '내보내는 중...';
spread.export(function(blob) {
downloadXlsxBlob(blob, '계리_리포트_값만.xlsx', status, '✅ 내보내기 완료 — 값만 저장 (계리 함수 수식은 제거되어 결과만 공유됨)');
}, function(e) {
console.error(e);
if (status) status.textContent = '❌ 내보내기 실패';
}, {
fileType: GC.Spread.Sheets.FileType.excel,
includeFormulas: false
});
});
// ── Excel 가져오기: 가져온 뒤 계리 함수 수식이 실제로 재계산되는지 셀 값으로 검수 ──
document.getElementById('btnImport')?.addEventListener('click', function() {
const fileInput = document.getElementById('fileInput');
const file = fileInput?.files[0];
if (!file) { alert('xlsx 파일을 선택하세요.'); return; }
const status = document.getElementById('importStatus');
if (status) status.textContent = '가져오는 중...';
spread.import(file, function() {
const check = spread.getActiveSheet().getValue(10, 1);
const ok = typeof check === 'number' && !isNaN(check);
if (status) {
status.textContent = ok
? `✅ 가져오기 완료 — 계리 함수 정상 재계산 확인 (ANNUITYPV = ${check.toFixed(4)})`
: '⚠️ 가져오기는 완료됐지만 계리 함수 결과를 확인할 수 없습니다 (#NAME? 등)';
}
}, function(e) {
console.error(e);
if (status) status.textContent = '❌ 가져오기 실패';
}, {
fileType: GC.Spread.Sheets.FileType.excel
});
});