/* 현재 페이지의 엑셀 값을 가져오는 Function
* @Param : Object, Array, Array, Array, String
* @Return : Excel Download*/
Excel($list, gridRows, acceptHeader, acceptData, excelName) {
// 현 페이지의 jQGrid Id Array
const dataIds = $list.getDataIDs();
// 전체 페이지의 jQGrid Id Object
const idToDataIndex = $list.jqGrid('getGridParam','_index');
const data = $list.getRowData(dataIds[0]);
const colNames = [];
const fileName = excelName;
// idToDataIndex는 Object이기 때문에 Array로 변경
let idsArr = [];
for (let id in idToDataIndex) {
if (idToDataIndex.hasOwnProperty(id)) {
idsArr.push(id);
}
}
let index = 0;
for (let element in data) {
for (let i = 0; i < acceptData.length; i++) {
const acceptKey = acceptData[i];
if (element === acceptKey) {
colNames[index++] = element;
}
}
}
// 컬럼 헤더 가져오기
const columnHeader = $list.jqGrid('getGridParam', 'colNames') + '';
const arrHeader = columnHeader.split(',');
let html = '<table border=1><tr>';
/* 정해진 Header 입력 */
for (let i = 0; i < acceptHeader.length; i++) {
html += `<td><b>${acceptHeader[i]}</b></td>`;
}
html += '</tr>';
// 값 불러오기
for (let i = 0; i < idsArr.length; i++) {
const rowData = gridRows[i];
/**
* 이 부분에서 데이터 수정 처리하기
**/
html = html + "<tr>";
for (let j = 0; j < colNames.length; j++) {
/* rowData의 값이 null일 경우를 방지 */
if (rowData[colNames[j]] === null) {
rowData[colNames[j]] = '';
}
html += `<td>${rowData[colNames[j]]}</td>`;
}
html += '</tr>';
}
html += '</table>';
/* DownLoad */
const dataType = 'data:application/vnd.ms-excel;charset=utf-8';
const tableHtml = encodeURIComponent(html);
const a = document.createElement('a');
a.href = datyType + ',%EF%BB%BF' + tableHtml;
a.download = fileName + '.xls';
a.click();
}
Server단을 타지 않고 jQgrid로만으로 Excel을 export하는 방법이다.
$list는 Grid, gridRows는 loadComplete(data)의 data, acceptHeader는 엑셀에 들어갈 헤더(ColModel), acceptData는 DB와 매칭되는 이름(ColName), excelName은 출력할 엑셀의 파일 이름
그냥 간단하게 출력하는 방법은 더 간단하게 작성할 수 있으나, 제외하는 조건을 추가해야 하기 때문에 위와 같이 작성함.