! 제품 버전을 정확하게 입력해 주세요.
제품 버전이 정확하게 기재되어 있지 않은 경우,
최신 버전을 기준으로 안내 드리므로
더욱 빠르고 명확한 안내를 위해
제품 버전을 정확하게 입력해 주세요!

웹 응용 프로그램에 JavaScript Excel XLSX 뷰어를 추가하는 방법 > 온라인 스터디

본문 바로가기

고급기능 웹 응용 프로그램에 JavaScript Excel XLSX 뷰어를 추가하는 방법

페이지 정보

작성자 GrapeCity 작성일 2023-10-10 09:28 조회 168회 댓글 0건

본문

첨부파일

JavaScript로 Excel 뷰어를 만드는 작업은 생각보다 까다롭습니다. 


하지만, SpreadJS (JavaScript 스프레드시트)를 이용한다면 아주 간단하고 빠르게 Excel 뷰어를 생성할 수 있습니다.

이번 스터디에서는 SpreadJS를 활용해, 웹 브라우저에서 Excel 파일을 열고 저장할 수 있는 뷰어를 만드는 방법과, 시트가 편집되지 않도록 보호하고 암호를 추가하는 방법에 대해 알아볼 것입니다.


샘플을 다운로드하여 함께 진행해 주시길 바랍니다.



SpreadJS 시작하기 


이 프로젝트는 HTML, JavaScript 파일, CSS 파일 등 세 개의 파일로 작성됩니다.


SpreadJS를 프로젝트에 통합하는 것부터 시작합니다.

다음과 같은 몇 가지 방법을 확인하여 작업을 수행해 봅시다.


SpreadJS 파일 참조


1) 로컬 파일 참조

GrapeCity 웹 사이트에서 SpreadJS를 다운로드하여 응용 프로그램을 가지고 올 수 있습니다.


다운로드 이후 ZIP 파일 압축을 풀어 JS 및 CSS 파일들을 애플리케이션에 복사할 수 있습니다.

  • gc.spread.sheets.all.xx.x.x.min.js

  • gc.spread.sheets.io.xx.x.x.min.js

  • gc.spread.sheets.excel2013white.xx.x.x.css


다음 파일을 응용 프로그램 폴더에 추가하면 코드에서 참조할 수 있습니다.

<link rel="stylesheet" type="text/css" href="./styles/gc.spread.sheets.excel2013white.css">
<script src="./scripts/gc.spread.sheets.all.min.js" type="text/javascript"></script>
<script src="./scripts/gc.spread.sheets.io.min.js" type="text/javascript"></script>
<script src="./scripts/gc.spread.sheets.charts.min.js" type="text/javascript"></script>
<script src="./scripts/gc.spread.sheets.shapes.min.js" type="text/javascript"></script>


2) NPM 참조  


NPM 파일을 통해 SpreadJS를 참조할 수도 있습니다.


SpreadJS를 참조할 수 있는 또다른 방법은 NPM 파일을 이용하는 것입니다.


응용 프로그램에 다음 명령을 추가합니다.

npm install @grapecity/spread-sheets @grapecity/spread-sheets-io @grapecity/spread-sheets-charts @grapecity/spread-sheets-shapes @grapecity/spread-sheets-pivots


코드에서 파일을 참조할 수 있습니다.

<link rel="stylesheet" type="text/css" href="./node_modules/@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css">
<script src="./node_modules/@grapecity/spread-sheets/dist/gc.spread.sheets.all.min.js" type="text/javascript"></script>
<script src="./node_modules/@grapecity/spread-sheets-io/dist/gc.spread.sheets.io.min.js" type="text/javascript"></script>
<script src="./node_modules/@grapecity/spread-sheets-charts/dist/gc.spread.sheets.charts.min.js" type="text/javascript"></script>
<script src="./node_modules/@grapecity/spread-sheets-shapes/dist/gc.spread.sheets.shapes.min.js" type="text/javascript"></script>


HTML 콘텐츠 만들기


파일이 참조되면 HTML 페이지와 CSS 스타일을 조합할 수 있습니다.


우리는 미리 만들어 둔 스타일을 사용해 보겠습니다.

body {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

.sample-tutorial {
    position: relative;
    height: 100%;
    overflow: hidden;
}

.sample-container {
    width: calc(100% - 280px);
    height: 100%;
    float: left;
}

.sample-spreadsheets {
    width: 100%;
    height: calc(100% - 25px);
    overflow: hidden;
}

.options-container {
    float: right;
    width: 280px;
    height: 100%;
    box-sizing: border-box;
    background: #fbfbfb;
    overflow: auto;
}

.sample-options {
    z-index: 1000;
}

.inputContainer {
    width: 100%;
    height: auto;
    border: 1px solid #eee;
    padding: 6px 12px;
    margin-bottom: 10px;
    box-sizing: border-box;
}

.settingButton {
    color: #fff;
    background: #82bc00;
    outline: 0;
    line-height: 1.5715;
    position: relative;
    display: inline-block;
    font-weight: 400;
    white-space: nowrap;
    text-align: center;
    height: 32px;
    padding: 4px 15px;
    font-size: 14px;
    border-radius: 2px;
    user-select: none;
    cursor: pointer;
    border: 1px solid #82bc00;
    box-sizing: border-box;
    margin-bottom: 10px;
    margin-top: 10px;
}

.settingButton:hover {
    color: #fff;
    border-color: #88b031;
    background: #88b031;
}

.settingButton:disabled {
    background: #e2dfdf;
    border-color: #ffffff;
}

.options-title {
    font-weight: bold;
    margin: 4px 2px;
}

#selectedFile {
    display: none;
}

select, input[type="text"], input[type="number"] {
    display: inline-block;
    margin-left: auto;
    width: 120px;
    font-weight: 400;
    outline: 0;
    line-height: 1.5715;
    border-radius: 2px;
    border: 1px solid #F4F8EB;
    box-sizing: border-box;
}

.passwordIpt {
    margin-top: 10px;
    height: 25px;
}

.passwordIpt[warning="true"] {
    border-color: red;
}

.passwordIpt[warning="true"]::placeholder {
    color: red;
    opacity: 0.8;
}

@keyframes shake {
    0% { transform: translate(1px, 1px) rotate(0deg); }
    10% { transform: translate(-1px, -2px) rotate(-1deg); }
    20% { transform: translate(-3px, 0px) rotate(1deg); }
    30% { transform: translate(3px, 2px) rotate(0deg); }
    40% { transform: translate(1px, -1px) rotate(1deg); }
    50% { transform: translate(-1px, 2px) rotate(-1deg); }
    60% { transform: translate(-3px, 1px) rotate(0deg); }
    70% { transform: translate(3px, 1px) rotate(-1deg); }
    80% { transform: translate(-1px, -1px) rotate(1deg); }
    90% { transform: translate(1px, 2px) rotate(0deg); }
    100% { transform: translate(1px, 1px) rotate(0deg); }
}

#warningBox {
    color: red;
}


다음으로, 응용 프로그램에 필요한 버튼과 UI를 추가할 수 있습니다.

  • SpreadJS 인스턴스

  • 상태 표시줄

  • 가져오기 섹션

    • 암호 텍스트 상자

    • 파일 선택 버튼

    • 가져오기 버튼

  • 내보내기 섹션

    • 암호 텍스트 상자

    • 내보내기 버튼


각 요소에 적절한 스타일을 사용하여 HTML 본문 섹션에 추가해 보겠습니다.

<body>
    <div class="sample-tutorial">
        <div class="sample-container">
            <div id="ss" class="sample-spreadsheets"></div>
            <div id="statusBar"></div>
        </div>
        <div class="options-container">
            <div class="option-row">
                <div class="inputContainer">
                    <div class="options-title">Import:</div>
                    <input class="passwordIpt" id="importPassword" type="password" placeholder="Password" disabled>
                    <br>
                    <div id="warningBox"></div>
                    <input id="selectedFile" type="file" accept=".xlsx" />
                    <button class="settingButton" id="selectBtn">Select</button>
                    <button class="settingButton" id="importBtn" disabled>Import</button>
                </div>
                <div class="inputContainer">
                    <div class="options-title">Export:</div>
                    <input class="passwordIpt" id="exportPassword" type="password" placeholder="Password">
                    <br>
                    <button class="settingButton" id="exportBtn">Export</button>
                </div>
            </div>
        </div>
    </div>
</body>


SpreadJS 초기화


우리는 지금까지 파일을 참조하고 HTML 콘텐츠를 설정했습니다.


이제, SpreadJS 인스턴스를 초기화하고 app.js 파일에 Excel 가져오기 코드를 추가하겠습니다. 


JavaScript window.onload 함수에 넣을 수 있습니다.

window.onload = function () {
  let spread = new GC.Spread.Sheets.Workbook(document.getElementById("ss"));
}


버튼 및 기능 추가


응용 프로그램의 목적을 위해 window.onload 함수 이전에 생성한 UI에 활용할 수 있는 몇 가지 변수를 생성하겠습니다. 

이 작업은 작성을 더욱 쉽게 만들 것입니다.

const $ = selector => document.querySelector(selector);
const listen = (host, type, handler) => host.addEventListener(type, handler);


window.onload 함수 내 다양한 HTML 요소를 보다 더 쉽게 참조하는 변수를 만들어 보겠습니다.

const importPassword = $('#importPassword');
const selectBtn = $('#selectBtn');
const fileSelect = $('#selectedFile');
const importBtn = $('#importBtn');
const warningBox = $('#warningBox');
const exportPassword = $('#exportPassword');
const exportBtn = $('#exportBtn');


이제 파일 선택 버튼 및 암호 텍스트 상자를 위한 이벤트 리스너와 함수 그리고 잘못된 암호 메시지를 위한 핸들러를 추가할 수 있습니다.

listen(selectBtn, "click", () => fileSelect.click());

const fileSelectedHandler = () => {
    importPassword.disabled = false;
    importBtn.disabled = false;
}

listen(fileSelect, 'change', fileSelectedHandler);

const wrongPasswordHandler = message => {
    importPassword.setAttribute('warning', true);
    importPassword.style.animation = "shake 0.5s";
    setTimeout(() => importPassword.style.animation = "", 500);
    warningBox.innerText = message;
    importPassword.value = '';
};

listen(importPassword, 'focus', () => {
    warningBox.innerText = '';
    importPassword.removeAttribute('warning');
});



SpreadJS로 Excel 파일 가져오기


Excel 파일을 SpreadJS 인스턴스로 가지고 오는 코드를 추가하겠습니다.


SpreadJS import 함수를 호출할 때 암호로 보호된 파일을 가지고 오는 경우가 생길 수 있기 때문에 이를 고려해야 합니다.


함수를 작성한 후, 이벤트 핸들러를 추가합니다.

const importFileHandler = () => {
    let file = fileSelect.files[0];
    if (!file) return ;
    spread.import(file, console.log, error => {
        if (error.errorCode === GC.Spread.Sheets.IO.ErrorCode.noPassword || error.errorCode === GC.Spread.Sheets.IO.ErrorCode.invalidPassword) {
            wrongPasswordHandler(error.errorMessage);
        }
    }, {
        fileType: GC.Spread.Sheets.FileType.excel,
        password: importPassword.value
    });
};
listen(importBtn, 'click', importFileHandler);



SpreadJS에서 Excel 파일 내보내기


가져오기와 마찬가지로 내보낼 때, Excel 파일에 암호를 추가할 수 있도록 지원합니다.


SpreadJS export 함수에 암호를 전달하기만 하면 됩니다.


이를 위한 이벤트 핸들러도 추가하겠습니다.

const exportFileHandler = () => {
        let password = exportPassword.value;
        spread.export(blob => saveAs(blob, (password ? 'encrypted-' : '') + 'export.xlsx'), console.log, {
            fileType: GC.Spread.Sheets.FileType.excel,
            password: password
        });
    };
    listen(exportBtn, 'click', exportFileHandler);



데이터 보호


또한, 사용자가 변경할 수 없도록 데이터를 보호할 수도 있습니다.


그렇게 하려면 통합 문서의 현재 시트를 보호하는 버튼을 추가해야 합니다.


이번 샘플에서는 목적에 맞게 활성 시트가 되겠지만, 이는 다른 요구 사항이 생길 시, 종류에 따라 변경할 수 있습니다.


다른 버튼과 마찬가지로 버튼 클릭에 대한 핸들러를 추가해야 합니다.

SpreadJS를 사용할 경우 다음과 같은 보호 옵션도 지정할 수 있습니다.

const protectHandler = () => {
    var option = {
        allowSelectLockedCells:true,
        allowSelectUnlockedCells:true,
        allowFilter: true,
        allowSort: false,
        allowResizeRows: true,
        allowResizeColumns: false,
        allowEditObjects: false,
        allowDragInsertRows: false,
        allowDragInsertColumns: false,
        allowInsertRows: false,
        allowInsertColumns: false,
        allowDeleteRows: false,
        allowDeleteColumns: false,
        allowOutlineColumns: false,
        allowOutlineRows: false
    };
    spread.getSheet(0).options.protectionOptions = option;
    spread.getSheet(0).options.isProtected = true;
};
listen(protectBtn, 'click', protectHandler);



응용 프로그램 실행 


이제 응용 프로그램을 실행하면 됩니다.


PureJS 및 HTML을 사용하여 응용 프로그램을 만들었기 때문에 웹 브라우저에서 간단하게 HTML 파일을 열 수 있습니다.

JavaScript Excel XLSX 뷰어


'선택(Select)' 버튼을 클릭하여 로드할 Excel 파일을 선택합니다.


'가져오기(Import)' 버튼을 클릭하여 SpreadJS로 가지고 옵니다.

JavaScript Excel XLSX 뷰어


이제 내보내기 아래의 암호 텍스트 상자에 비밀번호를 입력합니다.


'내보내기(Export)' 버튼을 클릭하여 암호를 추가할 수 있습니다.

JavaScript Excel XLSX 뷰어


SpreadJS를 사용해 여러분들만의 Excel 뷰어를 만들어 보았습니다!


이 뷰어를 사용하면 몇 가지 간단한 단계만으로 Excel 파일을 열고, 보호하고, 암호를 추가한 다음 내보낼 수 있습니다.


자세한 내용은 데모도움말 통해 확인해 주세요!






지금 바로 SpreadJS를 다운로드하여 직접 테스트해 보세요!


  • 페이스북으로 공유
  • 트위터로  공유
  • 링크 복사
  • 카카오톡으로 보내기

댓글목록

등록된 댓글이 없습니다.

메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기

태그1

메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기
이메일 : sales-kor@mescius.com | 전화 : 1670-0583 | 경기도 과천시 과천대로 7길 33, 디테크타워 B동 1107호 메시어스(주) 대표자 : 허경명 | 사업자등록번호 : 123-84-00981 | 통신판매업신고번호 : 2013-경기안양-00331 ⓒ 2024 MESCIUS inc. All rights reserved.