[]
다음 섹션에서는 Excel(.xlsx) 파일과 JSON 파일(json 또는 ssjson)을 SpreadJS에 가져오는 절차를 설명합니다.
SpreadJS API 외에도 다음과 같은 메서드들이 사용됩니다.
ExcelIO를 생성하려면 HTML의 HEAD 태그에 ExcelIO 스크립트 파일에 대한 참조를 추가하세요.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8"/>
<meta name = "viewport" content = "width = device-width, initial-scale = 1.0"/>
<!- a) SpreadJS scripts 및 CSS 추가 ->
<!-A1) SpreadJS script 파일 추가 ->
<script type = "text/javascript"
src = "SpreadJS\gc.spread.sheets.all.xxxmin.js" > </script>
<!-A2) CSS 파일 추가 ->
<script type="text/css"
src = "SpreadJS\gc.spread.sheets.x.x.x.css"> </script>
<!-D1) ExcelIO script 파일 추가 ->
<script type = "text/javascript"
src = "SpreadJS\gc.spread.excelio.xxxmin.js"> </script>
<style>
.spread-container {
height: 550px;
}
</style>
</head>
<body>
<h1> Import files into SpreadJS </h1>
<div class = "sample-container" >
<!-B) SpreadJS 대상 DOM 요소 생성하기 ->
<div id = "ss" class = "spread-container"> </div>
</div>
</body>
<script>
// c) "ss" ID를 가진 div로 SpreadJS 컨테이너를 초기화합니다.
window.onload = function ()
{
var spread = new GC.Spread.Sheets.Workbook (
document.getElementById ("ss"),
{sheetCount: 1}
);
// d2) ExcelIO 인스턴스 생성하기
excelIO = new GC.Spread.Excel.IO ();
};
</script>
</html>
fromJSON 메서드를 사용해 지정한 JSON 문자열에서 Spread 인스턴스를 불러오는 importJSON 함수를 만듭니다.
워크북 컴포넌트에 포커스를 맞추기 위해 focus 메서드를 사용하세요.
// importJSON() 함수 생성
function importJSON(spreadJson) {
var ss = GC.Spread.Sheets.findControl(document.getElementById("ss"));
if (spreadJson.version && spreadJson.sheets) {
// spreadJSON이라는 JSON 문자열에서 객체를 불러옵니다.
ss.fromJSON(spreadJson);
// 워크북 컴포넌트에 포커스를 맞춥니다.
ss.focus();
}
}
importSpreadFromExcel 함수를 만들고, excelIO.open 메서드를 호출하여 Excel 파일을 JSON 문자열로 변환해 가져옵니다.
excelIO.open 메서드로 생성된 JSON 데이터 문자열에서 SpreadJS 인스턴스를 불러오기 위해 importJSON 함수를 호출합니다.
// importSpreadFromExcel() 함수 생성
function importSpreadFromExcel(file, options) {
// Excel 파일을 불러와 SpreadJS 인스턴스에 반영합니다.
excelIO.open(
file,
function (json) {
// 1단계에서 만든 importJSON() 함수를 호출하여 Excel 파일을 가져옵니다.
importJSON(json);
},
function (e) {
console.log(e);
},
options
);
}
importSpreadFromJSON 함수를 만들어 JSON 파일을 가져옵니다.
새로운 FileReader를 생성하여 'reader' 변수에 저장합니다.
FileReader의 readAsText 함수를 사용해 JSON 파일 내용을 문자열로 읽습니다. FileReader가 완료되면 onload 이벤트가 발생합니다.
importSuccessCallback 함수를 호출해 JSON.parse 메서드로 결과를 자바스크립트 객체로 파싱합니다.
// importSpreadFromJSON() 함수 생성
function importSpreadFromJSON(file) {
function importSuccessCallback(responseText) {
// JSON 문자열 파싱
var spreadJson = JSON.parse(responseText);
// 파싱된 JSON 문자열에서 SpreadJS 인스턴스를 불러오기 위해 importJSON 메서드를 실행합니다.
importJSON(spreadJson);
}
// JSON 문자열을 읽을 파일 객체도 생성합니다.
var reader = new FileReader();
// 아래 readAsText()가 완료되면, 성공 콜백을 반환하는 이벤트가 발생합니다.
reader.onload = function () {
importSuccessCallback(this.result);
};
// readAsText() 메서드를 실행합니다.
// 이 작업은 파일 내용을 읽고, 완료되면 load 이벤트가 발생합니다.
reader.readAsText(file);
return true;
}
importFile 함수를 생성하여, 가져온 파일 이름을 매개변수로 받아 파일 형식을 판단합니다. 파일 이름에서 마지막 "."의 위치를 찾아 Excel 파일인지 JSON 파일인지 구분합니다.
importFile 함수 내에 If/Else 문을 작성하여, 파일 형식에 따라 importSpreadFromJSON 또는 importSpreadFromExcel 함수를 호출하도록 만듭니다.
// importFile() 함수를 만들어, 파일이 .xlsx인지 .json 또는 .ssjson인지 판단하도록 합니다.
function importFile(file) {
// 선택한 파일의 이름을 가져옵니다.
var fileName = file.name;
// 파일 이름에서 마지막 "."의 인덱스 위치를 구합니다.
var index = fileName.lastIndexOf(".");
// 마지막 "."의 인덱스 이후 부분, 즉 파일 확장자를 반환합니다.
var fileExt = fileName.substr(index + 1).toLowerCase();
// 파일 확장자에 따라 호출할 import Spread 함수를 결정합니다.
if (fileExt === "json" || fileExt === "ssjson") {
importSpreadFromJSON(file);
} else if (fileExt === "xlsx") {
importSpreadFromExcel(file);
}
}
HTML의 id가 fileSelector 인 input에서 파일을 선택할 때 importFile 함수를 실행하는 processFileSelected 함수를 만듭니다.
<body>
<h1>Section 3: Importing files to SpreadJS</h1>
<div>
Select file to import:
<input type="file" onchange="processFileSelected()" id="fileSelector" />
</div>
<br />
<div id="ss" style="height:700px;width:900px"></div>
</body>
// processFileSelected() 함수 생성
function processFileSelected() {
// id가 fileSelector인 HTML 입력 요소에서 선택한 파일을 가져옵니다.
var fileSelector = document.getElementById("fileSelector");
var file = fileSelector.files[0];
if (!file) return false;
fileSelector.innerHTML = "";
// 파일이 선택되면 importFile() 함수를 실행합니다.
return importFile(file);
}
위 코드의 출력 결과는 아래와 같습니다:
엑셀 파일 가져오기
JSON 파일 가져오기