[jQgrid] Excel Export(2)

INO·2022년 3월 30일
0

jQgrid

목록 보기
9/9
post-thumbnail
/** Excel Function
 *  @Param : Object, String*/
function AutoExcel($list, fileName) {
	/* Get Data (loadComplete) */
	const rows = $list.data('rows');
	const colNames = $list.jqGrid('getGridParam', 'colNames');
	const colModel = $list.jqGrid('getGridParam', 'colModel');
	const headData = [];

	/* Sort Data (Header) */
	colModel.forEach((col, index) => {

		/* Exclude No Data */
		for (let i = 0; i < rows.length; i++) {
			const row = rows[i];

			if (!col.hidden && col.index !== undefined && row[col.index] !== undefined) {
				headData.push({
					key: col.index,
					name: colNames[index]
				});
				break;
			}
		}
	});

	/* Set Table  */
	let excel = '<table border="1px"><tr>';

	/* thead */
	for (let key in headData) {
		excel += `<th>${headData[key].name}</th>`;
	}
	excel += '</tr>';

	/* tbody */
	rows.forEach(row => {
		excel += '<tr>';

		for (let key in headData) {
			const rowKey = headData[key].key;
			let cell = row[rowKey];
			
			/* check falsy value*/
            if (cell === null || cell === undefined) cell = '';

			excel += `<td style="mso-number-format:\\@">${String(cell)}</td>`;
		}
		excel += '</tr>';
	});

	excel += "</table>";

	/* DownLoad */
	const dataType = 'data:application/vnd.ms-excel;charset=utf-8';
	const tableHtml = encodeURIComponent(excel);
	const a = document.createElement('a');
	a.href = dataType + ',%EF%BB%BF' + tableHtml;
	a.download = fileName + '.xls';
	a.click();
}

loadComplete에서 data를 담아논 후 넘기게 되면 현재 화면에서 보는 Grid 데이터를 그대로 엑셀로 반환받을 수 있다.

const rows = $list.data('rows');

Grid를 reload시키는 경우 해당 loadComplete에서 값이 변환될 수 있도록 담아주어야 한다.

formatter를 사용하여 값을 분기시키는 것보다 SQL에서 case when then을 사용하는 것에 더 적합하다고 생각한다.

기존에 있던 Excel Export 방식보다 자동이다.

profile
🎢

0개의 댓글