JavaScript로 엑셀 팝업만들기 - SpreadJS 사용법

 

SpreadJS 쓸 일이 생겨서

쓰는 김에 정리해본다.

공식 사이트를 보고 참고했으니

다들 참고하셔서 보시면 좋을 것 같다.

 

 

Demos | SpreadJS JavaScript Demos

Learn how you can easily add advanced spreadsheet capabilities to your JavaScript applications today to create financial, analysis, budgeting, forecasting, data collection, scientific and many other similar applications. Begin by selecting a featured demo

www.grapecity.com

 

우선 프론트 연결까지만 만들어 볼 것이기때문에

백 부분은 컨트롤러 정도만 만들었다.

 

참고 사이트에 있는 Pivot Table - Overview의 

index.html 과 app.js 부터 살펴보자

<index.html>

<!doctype html>
<html style="height:100%;font-size:14px;">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="$DEMOROOT$/en/purejs/node_modules/@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css">
    <script src="$DEMOROOT$/en/purejs/node_modules/@grapecity/spread-sheets/dist/gc.spread.sheets.all.min.js" type="text/javascript"></script>
    <script src="$DEMOROOT$/en/purejs/node_modules/@grapecity/spread-sheets-shapes/dist/gc.spread.sheets.shapes.min.js" type="text/javascript"></script>
    <script src="$DEMOROOT$/en/purejs/node_modules/@grapecity/spread-sheets-pivot-addon/dist/gc.spread.pivot.pivottables.min.js" type="text/javascript"></script>
    <script src="$DEMOROOT$/spread/source/js/license.js" type="text/javascript"></script>
    <script src="$DEMOROOT$/spread/source/data/pivot-data.js" type="text/javascript"></script>
    <script src="app.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
    <div class="sample-tutorial">
        <div id="ss" class="sample-spreadsheets"></div>
        <div id="optionContainer" class="optionContainer">
        </div>
    </div>
</html>

<app.js>

window.onload = function () {
    let spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"), {sheetCount: 4});//시트 생성
    initSpread(spread);// 시트 초기화
};
// 시트초기화 함수
function initSpread(spread) { 
    spread.suspendPaint();
    let sheet1 = spread.getSheet(0);
    let sheet2 = spread.getSheet(1);
    let sheet3 = spread.getSheet(2);
    let sheet4 = spread.getSheet(3);
    let tableName = getDataSource(sheet4, pivotSales);
    initPivotTable(sheet1, tableName);
    addCustom(sheet2, tableName);
    initBlankPivot(sheet3, tableName);
    columnFit(sheet4,0,6,100);
    spread.resumePaint();
}
//시트에 넣을 데이터 소스 함수
function getDataSource(sheet, tableSource){
    sheet.name("DataSource");
    sheet.setRowCount(117);
    sheet.getCell(-1, 0).formatter("YYYY-mm-DD");
    sheet.getRange(-1,4,0,2).formatter("$ #,##0");
        let table = sheet.tables.add('table', 0, 0, 117, 6);

    for(let i=2;i<=117;i++)
    {
      sheet.setFormula(i-1,5,'=D'+i+'*E'+i)
    }
    table.style(GC.Spread.Sheets.Tables.TableThemes["none"]);
    sheet.setArray(0, 0, tableSource);
    return table.name();
}

function addCustom(sheet, tableName){
    sheet.name("Custom PivotTable");
    sheet.setRowCount(1000);
    let pivotTableOptions = {bandRows:true,bandColumns:true};
    let pivotTable = sheet.pivotTables.add("CustomPivotTable", tableName, 1, 1, GC.Spread.Pivot.PivotTableLayoutType.tabular, GC.Spread.Pivot.PivotTableThemes.light8, pivotTableOptions);
    pivotTable.suspendLayout();
    pivotTable.add("salesperson", "Salesperson", GC.Spread.Pivot.PivotTableFieldType.rowField);
    pivotTable.add("car", "Cars", GC.Spread.Pivot.PivotTableFieldType.rowField);
    pivotTable.add("date", "Date", GC.Spread.Pivot.PivotTableFieldType.columnField);
    pivotTable.add("total", "Totals", GC.Spread.Pivot.PivotTableFieldType.valueField, GC.Pivot.SubtotalType.sum);
    let itemList = ["Alan","John", "Tess"];
    pivotTable.labelFilter("Salesperson", { textItem: { list: itemList, isAll: false } });
    pivotTable.sort("Salesperson", { sortType: GC.Pivot.SortType.asc });
    let carList = ["Audi","BMW","Mercedes"];
    pivotTable.labelFilter("Cars", { textItem: { list: carList, isAll: false } });
    pivotTable.sort("Cars", { sortType: GC.Pivot.SortType.asc });
    let style = new GC.Spread.Sheets.Style();
    style.formatter = "$ #,##0";
    pivotTable.setStyle({dataOnly: true}, style);
    pivotTable.resumeLayout();
    pivotTable.autoFitColumn();
}

function initBlankPivot(sheet, source){
    sheet.name("Blank PivotTable");
    sheet.setColumnWidth(0, 20);
    sheet.pivotTables.add("BlankPivotTable", source, 1, 1, GC.Spread.Pivot.PivotTableLayoutType.outline, GC.Spread.Pivot.PivotTableThemes.medium4);
}

function initPivotTable(sheet, tableName){
    sheet.name("Basic PivotTable");
    sheet.setRowCount(1000);
    let pivotTableOptions = {bandRows:true,bandColumns:true};
    let pivotTable = sheet.pivotTables.add("PivotTable", tableName, 1, 1, GC.Spread.Pivot.PivotTableLayoutType.outline, GC.Spread.Pivot.PivotTableThemes.medium1, pivotTableOptions);
    pivotTable.suspendLayout();
    pivotTable.add("salesperson", "Salesperson", GC.Spread.Pivot.PivotTableFieldType.rowField);
    pivotTable.add("car", "Cars", GC.Spread.Pivot.PivotTableFieldType.rowField);
    pivotTable.add("date", "Date", GC.Spread.Pivot.PivotTableFieldType.columnField);
    let groupInfo = { originFieldName: "date", dateGroups: [{ by: GC.Pivot.DateGroupType.quarters }] };
    pivotTable.group(groupInfo);
    pivotTable.add("total", "Totals", GC.Spread.Pivot.PivotTableFieldType.valueField, GC.Pivot.SubtotalType.sum);
    let style = new GC.Spread.Sheets.Style();
    style.formatter = "$ #,##0";
    pivotTable.setStyle({dataOnly: true}, style);
    pivotTable.resumeLayout();
    pivotTable.autoFitColumn();
}

function columnFit(sheet,start,end,width){
    for (let i = start; i < end; i++) {
        sheet.setColumnWidth(i, width);
    }
}

 

html 에서 head 태그 안에 있는 코드는 시트 스타일과 라이센스 연결해주는 것으로, 

복붙 해서 사용하면 되고 javaScript  부분에선

시트생성,  시트초기화, 데이터 소스

이 3가지만 우선 기억하면 된다.

 

 

우선 , 나는  홈 화면에 바로 띄울것이 아니라,

홈화면에 있는 버튼을 눌러서 엑셀창을 띄우는

엑셀 팝업형식을 만드는 것이기 때문에

html에서는 index.html, excelPop01.html 두가지 파일을 생성한다.

또한 excelPop01.html과 연결하여 spreadJS를 만들기 위해 app.js style.css 를 생성한다.

먼저 index.html 코드

<!doctype html>
<html style="height:100%;font-size:14px;">

<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body style="align-items: center;display: flex;flex-direction: column;justify-content: center;">
        <div class="option-row" style="background-color: green;  align-items: center;display: flex;flex-direction: column;justify-content: center;">
            <a href="javascript:openPop()" class="excel-sample-btn" id="excelButton" style="text-decoration:none;color: rgb(0,0,0);">
                <span class="txt" style="text-decoration:none;color: rgb(255,255,255);">Excel 팝업</span>
            </a>
        </div>
<script>
    function openPop() {
        options = {
            width: "106vh",
            height: "90vh"
        }
        window.open("/excelPop01",'sample',options);
    }
</script>
</body>
</html>

우선 기본 화면 버튼만 꾸미면 되니까 css 따로 안만들고 

그냥 태그 안에서 속성값들 주고

body 태그 안에  스크립트 넣어서 excelPop01 으로 가는 함수를 만들어서 연결해줬다.

style.css 는 엑셀 디자인이기때문에 참고사이트에서 그대로 가져와서 붙여줬고

app.js는  하나의 함수만 있으면 된다.

window.onload = function () {
    let spread = new GC.Spread.Sheets.Workbook(_getElementById('ss'), { sheetCount: 2 });
};

이렇게 하면 ss 아이디를 가진 element 를 잡아서 기본 시트 2개 인 엑셀을 생성해준다.

여기에 저장된 데이터를 불러 오고 싶으면

백 쪽에서 불러와서 index.html 에 함수호출하는 javascript 쪽에서

위 예문처럼 Datasource 로 보내주는 등 다양하게 활용가능하다.

방법이 별거 없긴 하지만 ..

엑셀양식이 필요할 땐 유용하게 사용될 라이브러리인것 같다 !

 

※ 배포 시에는 개발자 라이센스 구입해서 적용해야한다.

'Back > API' 카테고리의 다른 글

[API] JavaScript로 이메일 받기, 자동 회신 - EmailJS 사용법  (0) 2023.02.02