Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

blog

[DataTables] excel download 기능 추가 본문

Web/front-end

[DataTables] excel download 기능 추가

hjkongkong 2022. 2. 23. 20:40

이 템플릿을 사용하고있는데, 추가적으로 엑셀 다운로드 기능을 만들기위해 JS를 추가했다.

 DataTables CDN을 사용하면 쉽게 기능 적용이 가능한데, 무료 템플릿을 사용해서 템플릿에 구현되어있지 않은 기능은 CDN을 사용하면 전체 테이블의 css가 기본형태로 덮어써진다.

/resources/vendor/datatables에 필요한 js파일들을 넣어두고, script 부분에 button관련 js를 추가하였다.

Uncaught TypeError: Cannot read properties of undefined (reading 'defaults') at buttons.bootstrap4.min.js

해결방안 1. 같은 일을 하는 js가 동시에 호출된건 아닌가?
->실제로 템플릿을 가져다 써서 존재하는 js였는데 중복호출된 것이었음


해결방안 2. 호출 순서 변경
자바스크립트는 호출 순서를 지켜야한다. 그렇지 않으면 찾을 수 없음.

 

DataTables는 아주 친절한 공식사이트를 제공한다.

https://datatables.net/download/

 

Download

Download Compatibility A detailed compatibility table shows the browser's that DataTables supports and also which features of the extensions can be used with the other extensions. A few features may not always be fully compatible with every other aspect of

datatables.net

여기에서 DataTables / Buttons / HTML5export / JSZip / pdfmake을 클릭한 뒤 다운로드했다.

 

이렇게 추가

pdfmake를 추가했음에도 찾지 못함

호출 순서 변경!!

https://stackoverflow.com/questions/54873945/datatables-uncaught-typeerror-cannot-set-property-pdfmake-of-undefined

 

DataTables Uncaught TypeError: Cannot set property 'pdfMake' of undefined

I'm attempting to set up Datatables for a table. There is nothing particularly unusual about the table (content has been left blank in this example), and I believe I have included all the correct ...

stackoverflow.com

<script src="js/jquery-3.4.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/popper.min.js"></script>    
<script src="js/jquery.dataTables.min.js"></script> 
<script src="js/dataTables.buttons.min.js"></script>    
<script src="js/pdfmake.min.js"></script>   
<script src="js/buttons.html5.min.js"></script> 
<script src="js/buttons.print.min.js"></script>

이 순서로 호출해야한다.

 

이렇게 맞춰서 변경

$(document).ready(function() {
	$('#dataTable').DataTable({
	dom: 'Bfrtip',
	buttons: [
				{
					extend: 'excel'
					, text:  'Excel'
					, filename: 'export_excel'
					, title: 'Report'
				}
			]
	});
});

 

js 파일 작성하면...

투박한 버튼 완성

기존  bootstrap의 button class를 적용하려고한다.
옵션 레퍼런스를 참조

$(document).ready(function() {
	$('#dataTable').DataTable({
				dom: 'Bfrtip',
				buttons: [
							{
								extend: 'excel'
								, text: '<i class="fas fa-download"></i>'
								, filename: 'export_excel'
								, title: 'Report'
								, className: 'btn btn-primary btn-circle'
							}
						]
	});
});

적용 완료