java

SheetJS로 테이블을 엑셀로 저장하기

빈콩님 2022. 8. 10. 07:51

버튼 클릭 시 테이블을 엑셀로 저장해야하는데,
서버에서 할 필요가 없을 거 같아 찾아보니 sheetjs라는 좋은 js 발견 !
https://sheetjs.com/

SheetJS

SheetJS Tools for Excel Spreadsheets

sheetjs.com


간단하게 사용법을 적어두어야겠다.

1. SheetJS 파일 다운로드 & 스크립트 추가 또는 cdn 추가


두가지 방법이 있다. 나는 파일 다운로드 했슴.
Cdn은 버전 문제가 있을 수 있기 때무네 다운로드해서 사용하는 것을 추천.

1) SheetJS 파일 다운로드 & 스크립트 추가
- /dist/xlsx.full.min.js 다운받기
https://github.com/SheetJS/sheetjs

GitHub - SheetJS/sheetjs: 📗 SheetJS Community Edition -- Spreadsheet Data Toolkit

📗 SheetJS Community Edition -- Spreadsheet Data Toolkit - GitHub - SheetJS/sheetjs: 📗 SheetJS Community Edition -- Spreadsheet Data Toolkit

github.com

- 원하는 위치에 xlsx.full.min.js 저장 후 스크립트 추가하기

<script src="js/xlsx.full.min.js"></script>

2) cdn 추가

<script src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>


2. 테이블 생성

- 엑셀로 변경할 테이블 id 지정하기

<table id="excel_table">
   <thead>
     <tr>
       <th>한식</th>
       <th>양식</th>
     </tr>
   </thead>
   <tbody>
     <tr>
        <td>김치찌개</td>
    	 <td>치킨텐더샐러드</td>
     </tr>
     <tr>
    	 <td>제육볶음</td>
    	 <td>치킨텐더샐러드</td>
     </tr>
  </tbody>
</table>

3. 버튼 생성 & 파일 다운로드 추가

<button id="excel_btn" onclick="excelDown()">엑셀 다운로드</button>
// 테이블

<script>
function excelDown(){
  var fileNm = '파일명' + '.xlsx';
  var sheetNm = '시트명';
  var wb = XLSX.utils.table_to_book(document.getElementById('excel_table'), {sheet:sheetNM,raw:true});
  XLSX.writeFile(wb, (fileNm));
}
</script>



* 옵션

sheet - 시트명
raw - true는 숫자로 저장, false는 텍스트로 저장. false가 default

다양한 정보는
https://docs.sheetjs.com/

'java' 카테고리의 다른 글

getRemoteHost() 느릴 때 대체하기  (0) 2022.08.05