Java/실무
poi 로 엑셀 다운로드 구현하기
냠냠쿠
2024. 9. 10. 15:43
728x90
Table에 있는 데이터를 가져와 엑셀 다운로드를 구현해야했다.
<div>
<div>
<p> 그리드</p>
<div class="grid-btn-gap">
<button>전체 펼치기</button>
<button class="Table-info-all-btn ALL-search-btn excelDownload year-time-Grid" disabled>엑셀다운</button>
</div>
</div>
<div class="inline">
<table class="" id="">
<thead>
...
</thead>
<tbody id="tbodyData"></tbody>
</table>
</div>
...
대충 이렇게 생김
버튼을 누르면 형제 div인 inline안에 있는 table의 데이터를 가져와야함
//그리드 엑셀 다운로드
$(document).ready(function() {
// 엑셀 다운로드 버튼 클릭 이벤트
$('.excelDownload').on('click', function() {
// 버튼의 형제 요소 중 .inline을 찾고 그 아래의 table을 선택
var $table = $(this).closest('.ALL-main-item-laynout-head').siblings('.inline').find('table');
var data = [];
// 테이블 헤더 추출
var headers = [];
$table.find('thead th').each(function() {
var headerText = $(this).text();
});
data.push(headers);
// 테이블 바디 추출
$table.find('tbody tr').each(function() {
var row = [];
$(this).find('td').each(function() {
row.push($(this).text());
});
data.push(row);
});
$.ajax({
url: '/excelDownload',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
success: function(res) {
if (res.returnCode == "success") {
alert("다운로드 성공");
}else{
alert("다운로드 실패");
}
},
error: function( request, status, error ){
alert("status : " + request.status + ", message : " + request.responseText + ", error : " + error);
return;
}
});
});
});
// 엑셀파일 생성해서 각 PC의 다운로드 경로에 파일 다운
@RequestMapping(value = "/excelDownload")
public @ResponseBody Map<String , Object> excelDownload(@RequestBody List<List<String>> param) throws IOException {
System.out.println("/excelDownload");
HashMap<String, Object> retMap = new HashMap<String, Object>();
Map<String, Object[]> data = new TreeMap<>();
//C드라이브의 Downloads 파일에 저장되도록 함
String filePath = System.getProperty("user.home")+"/Downloads/";
//파일명 년월일시분초로 지정
LocalDateTime now = LocalDateTime.now();
String fileNm = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))+".xlsx";
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sheet1");
// 데이터의 각 행을 Map에 추가
for (int i = 0; i < param.size(); i++) {
List<String> row = param.get(i);
data.put(Integer.toString(i), row.toArray(new Object[0]));
}
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof String) {
cell.setCellValue((String)obj);
} else if (obj instanceof Integer) {
cell.setCellValue((Integer)obj);
}
}
}
try (FileOutputStream out = new FileOutputStream(new File(filePath, fileNm))) {
workbook.write(out);
retMap.put("returnCode", "success");
} catch (IOException e) {
e.printStackTrace();
retMap.put("returnCode", "fail");
}
return retMap;
}
참고한 블로그
https://velog.io/@dailylifecoding/Java-Apache-POI-simple-tutorial
[Java] Apache POI 간단 사용법
자바로 엑셀을 제어해보자. (feat.Apache POI)
velog.io
[Java] POI로 데이터 엑셀 다운받기
안녕하세요. 개발자 Jindory입니다. 오늘은 POI 라이브러리를 이용해서 엑셀 파일을 내려받는 과정에 대해서 글을 작성해보고자 합니다. 프로그램을 만들다 보면 데이터를 엑셀로 다운받아서 보고
jindory.tistory.com
https://lotuus.tistory.com/145
[SpringBoot] Apache Poi를 이용한 엑셀 다운로드 구현
목차 2022.12.03 내용 추가 아래 코드에서는 XSSFWorkbook을 사용하는데, 실제 운영서버에서 나는 Out Of Memory 에러를 경험했다. 편안한 주말을 보내고싶다면 꼭 반드시 아래 글을 읽어보고 SXSSFWorkbook을
lotuus.tistory.com
728x90