https://eblo.tistory.com/84
예전에 UI에서 간단하게 엑셀 파일을 내보내는 것을 해봤습니다.
그때는 그것만으로도 서버쪽 호출 안하고 간단하게 처리할 수 있어 좋아했는데 SheetJS는 배열, json, html 형태 등 다양한 형태의 데이터로 엑셀 파일을 생성해 줍니다. 정말 너무도 멋진 오픈 소스 같습니다.
2019/01/24 - [UI(Front-End)/javascript 일반] - 엑셀 다운로드 구현
1. 라이브러리 추가
<!-- jquery 추가, 필수아님 -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<!-- 필수, SheetJS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.3/xlsx.full.min.js"></script>
<!--필수, FileSaver savaAs 이용 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
2. 구현하기
전체 프로세스는
1. 엑셀 Workbook을 생성하고
2. 데이터(배열/json/html table) 가져와서 sheet 만들고
3. workbook에 만든 시트를 추가합니다.
4. 엑셀 파일을 만들고
5. 다운로드 받을 수 있게 처리합니다.
function exportExcel(){
// step 1. workbook 생성
var wb = XLSX.utils.book_new();
// step 2. 시트 만들기
var newWorksheet = excelHandler.getWorksheet();
// step 3. workbook에 새로만든 워크시트에 이름을 주고 붙인다.
XLSX.utils.book_append_sheet(wb, newWorksheet, excelHandler.getSheetName());
// step 4. 엑셀 파일 만들기
var wbout = XLSX.write(wb, {bookType:'xlsx', type: 'binary'});
// step 5. 엑셀 파일 내보내기
saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), excelHandler.getExcelFileName());
}
var excelHandler = {
getExcelFileName : function(){
return 'aoa-test.xlsx';
},
getSheetName : function(){
return 'AOA Test Sheet';
},
getExcelData : function(){
return [['이름' , '나이', '부서'],['도사원' , '21', '인사팀'],['김부장' , '27', '비서실'],['엄전무' , '45', '기획실']];
},
getWorksheet : function(){
return XLSX.utils.aoa_to_sheet(this.getExcelData());
}
}
function s2ab(s) {
var buf = new ArrayBuffer(s.length); //convert s to arrayBuffer
var view = new Uint8Array(buf); //create uint8array as viewer
for (var i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF; //convert to octet
return buf;
}
XLSX.utils 에서 제공하는 기능
Importing:
- aoa_to_sheet converts an array of arrays of JS data to a worksheet.
- json_to_sheet converts an array of JS objects to a worksheet.
- table_to_sheet converts a DOM TABLE element to a worksheet.
- sheet_add_aoa adds an array of arrays of JS data to an existing worksheet.
- sheet_add_json adds an array of JS objects to an existing worksheet.
예제 1. AOA(Array of array 배열형태) 데이터로 엑셀 파일 다운로드
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>sheetjs create xlsx excel example(array of array)</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.3/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script>
//공통
// 참고 출처 : https://redstapler.co/sheetjs-tutorial-create-xlsx/
function s2ab(s) {
var buf = new ArrayBuffer(s.length); //convert s to arrayBuffer
var view = new Uint8Array(buf); //create uint8array as viewer
for (var i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF; //convert to octet
return buf;
}
function exportExcel(){
// step 1. workbook 생성
var wb = XLSX.utils.book_new();
// step 2. 시트 만들기
var newWorksheet = excelHandler.getWorksheet();
// step 3. workbook에 새로만든 워크시트에 이름을 주고 붙인다.
XLSX.utils.book_append_sheet(wb, newWorksheet, excelHandler.getSheetName());
// step 4. 엑셀 파일 만들기
var wbout = XLSX.write(wb, {bookType:'xlsx', type: 'binary'});
// step 5. 엑셀 파일 내보내기
saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), excelHandler.getExcelFileName());
}
$(document).ready(function() {
$("#excelFileExport").click(function(){
exportExcel();
});
});
</script>
<script>
var excelHandler = {
getExcelFileName : function(){
return 'aoa-test.xlsx';
},
getSheetName : function(){
return 'AOA Test Sheet';
},
getExcelData : function(){
return [['이름' , '나이', '부서'],['도사원' , '21', '인사팀'],['김부장' , '27', '비서실'],['엄전무' , '45', '기획실']];
},
getWorksheet : function(){
return XLSX.utils.aoa_to_sheet(this.getExcelData());
}
}
</script>
</head>
<body>
파일 내보내기(배열) : <input type="button" id="excelFileExport" value="엑셀 파일 다운로드(배열)" />
</body>
</html>
예제 2. JSON 데이터로 엑셀 파일 다운로드
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>sheetjs create xlsx excel example(json)</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.3/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script>
//공통
// 참고 출처 : https://redstapler.co/sheetjs-tutorial-create-xlsx/
function s2ab(s) {
var buf = new ArrayBuffer(s.length); //convert s to arrayBuffer
var view = new Uint8Array(buf); //create uint8array as viewer
for (var i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF; //convert to octet
return buf;
}
function exportExcel(){
// step 1. workbook 생성
var wb = XLSX.utils.book_new();
// step 2. 시트 만들기
var newWorksheet = excelHandler.getWorksheet();
// step 3. workbook에 새로만든 워크시트에 이름을 주고 붙인다.
XLSX.utils.book_append_sheet(wb, newWorksheet, excelHandler.getSheetName());
// step 4. 엑셀 파일 만들기
var wbout = XLSX.write(wb, {bookType:'xlsx', type: 'binary'});
// step 5. 엑셀 파일 내보내기
saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), excelHandler.getExcelFileName());
}
$(document).ready(function() {
$("#excelFileExport").click(function(){
exportExcel();
});
});
</script>
<script>
var excelHandler = {
getExcelFileName : function(){
return 'json-test.xlsx';
},
getSheetName : function(){
return 'Json Test Sheet';
},
getExcelData : function(){
return [{'상품명':'삼성 갤럭시 s11' , '가격':'200000'}, {'상품명':'삼성 갤럭시 s12' , '가격':'220000'}, {'상품명':'삼성 갤럭시 s13' , '가격':'230000'}];
},
getWorksheet : function(){
return XLSX.utils.json_to_sheet(this.getExcelData());
}
}
</script>
</head>
<body>
파일 내보내기(JSON) : <input type="button" id="excelFileExport" value="엑셀 파일 다운로드(JSON)" />
</body>
</html>
예제 3. HTML TABLE로 엑셀 파일 다운로드
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>sheetjs create xlsx excel example(html table)</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.3/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script>
//공통
// 참고 출처 : https://redstapler.co/sheetjs-tutorial-create-xlsx/
function s2ab(s) {
var buf = new ArrayBuffer(s.length); //convert s to arrayBuffer
var view = new Uint8Array(buf); //create uint8array as viewer
for (var i=0; i<s.length; i++) view[i] = s.charCodeAt(i) & 0xFF; //convert to octet
return buf;
}
function exportExcel(){
// step 1. workbook 생성
var wb = XLSX.utils.book_new();
// step 2. 시트 만들기
var newWorksheet = excelHandler.getWorksheet();
// step 3. workbook에 새로만든 워크시트에 이름을 주고 붙인다.
XLSX.utils.book_append_sheet(wb, newWorksheet, excelHandler.getSheetName());
// step 4. 엑셀 파일 만들기
var wbout = XLSX.write(wb, {bookType:'xlsx', type: 'binary'});
// step 5. 엑셀 파일 내보내기
saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), excelHandler.getExcelFileName());
}
$(document).ready(function() {
$("#excelFileExport").click(function(){
exportExcel();
});
});
</script>
<script>
var excelHandler = {
getExcelFileName : function(){
return 'table-test.xlsx';
},
getSheetName : function(){
return 'Table Test Sheet';
},
getExcelData : function(){
return document.getElementById('tableData');
},
getWorksheet : function(){
return XLSX.utils.table_to_sheet(this.getExcelData());
}
}
</script>
</head>
<body>
<table id="tableData" style="border:1px solid #dddddd">
<thead>
<tr>
<th>이름</th>
<th>CP</th>
</tr>
</thead>
<tbody>
<tr>
<td>망나뇽</td>
<td>4000</td>
</tr>
<tr>
<td>마기라스</td>
<td>3900</td>
</tr>
<tr>
<td>해피너스</td>
<td>3800</td>
</tr>
</tbody>
</table>
파일 내보내기(HTML TABLE) : <input type="button" id="excelFileExport" value="엑셀 파일 다운로드(TABLE)" />
</body>
</html>
GITHUB
https://github.com/kkaok/examples/tree/master/jsExcelExample/src/main/resources/static/html
엑셀 파일 읽기 예제
2019/06/29 - [UI(Front-End)] - SheetJS : JS로 엑셀 파일 읽기 예제
댓글 0
| 번호 | 제목 | 글쓴이 | 날짜 | 조회 수 |
|---|---|---|---|---|
| 12 | [자바스크립트] 화상 자판을 덧붙인 온라인 한글 입력기 | proin | 2021.05.12 | 1 |
| 11 | [javascript]한글 가상 키보드 만들기 | proin | 2021.05.12 | 1 |
| 10 | Javascript - 비밀번호 유효성 검사 | proin | 2021.04.16 | 2 |
| 9 |
jquery 비 동기 통신 $.ajax(), $.get(), $.post() 사용방법
| proin | 2021.04.06 | 2 |
| 8 | [javascript•jQuery] 페이지 자동 새로고침 & 특정 div 영역 새로고침 | proin | 2021.04.06 | 2 |
| 7 |
[PHP] cmd (커맨드 명령어)를 실행하는 방법
| proin | 2021.04.06 | 2 |
| 6 | [jQuery] 실시간 업데이트(real time page update) | proin | 2021.04.06 | 1 |
| 5 | php에서 python script 실행하기 | proin | 2021.02.22 | 1 |
| 4 | jQuery - ajaxSubmit 사용법 및 유의사항(페이지 리로드 현상) | proin | 2021.01.20 | 1 |
| 3 | Ajax form submit 사용법 | proin | 2021.01.20 | 1 |
| 2 | javascript history 삭제 / href replace 비교 | proin | 2021.01.20 | 1 |
| » | SheetJS : JS로 엑셀 파일 쓰기 예제 | proin | 2020.04.24 | 1 |