HTML&JS/JS
JAVASCRIPT - EXCEL STYLING
워럭선생
2023. 9. 14. 10:29
반응형
Javascript를 기반으로 한 ExcelJS를 이용하여, Excel 파일 생성 및 Styling 방법
SheetJS를 사용할 경우, Styling이 안되는 문제가 있어 ExcelJS를 사용한다.
ExcelJS를 사용할 경우, Border 및 셀 내부에 색상 등을 설정할 수 있다.
각 셀별 Font 및 font 색상, 페이지 설정 등도 ExcelJS에서 지원한다.
Cell 위치는 'A1', ' C7' 같은 형식과 .getRow(5).getCell(3) 와 같이 column과 row 번호 형식 2가지로 지정할 수 있다.
For 문 등에서 cell 위치를 호출할때는 생각하면 .getRow(5).getCell(3) 형식을 사용하는 것이 보다 나은 듯 하다.
exceljs 관련 세부 내용 참고 : exceljs - npm (npmjs.com)
// Create Excel File
var wb = new ExcelJS.Workbook();
var ws = wb.addWorksheet('My Sheet');
// set column width
ws.getColumn(1).width = 30;
ws.getColumn(2).width = 60;
ws.getColumn(3).width = 90;
ws.getColumn(4).width = 10;
// define border style1
var sborder1 = {
top: {style:'medium', color: {argb:'FF00FF00'}},
left: {style:'medium', color: {argb:'FF00FF00'}},
bottom: {style:'medium', color: {argb:'FF00FF00'}},
right: {style:'medium', color: {argb:'FF00FF00'}}
};
// define border style2
var sborder2 = {
top: {style:'medium', color: {argb:'FF00FF00'}},
bottom: {style:'medium', color: {argb:'FF00FF00'}},
};
ws.getRow(3).getCell(3).border = sborder1; // apply border style
ws.getRow(3).getCell(3).value = 'asdfkpkppp'; // assign cell value
ws.getRow(5).getCell(3).border = sborder1;
// use string value of cell
getRow(5).getCell(3).value = 'asdfff';
ws.getRow(5).getCell(3).alignment = { horizontal:'center'} ;
var sfill1 = { type: 'pattern', pattern:'solid', fgColor : {argb:'FFD3D3D3'} };
var sfill2 = { type: 'pattern', pattern:'solid', fgColor : {argb:'FFA9A9A9'} };
var sfill3 = { type: 'pattern', pattern:'solid', fgColor : {argb:'FF808080'} };
var sfill4 = { type: 'pattern', pattern:'solid', fgColor : {argb:'FF696969'} };
ws.getRow(5).getCell(3).fill = sfill1;
ws.getRow(6).getCell(3).fill = sfill2;
ws.getRow(7).getCell(3).fill = sfill3;
ws.getRow(8).getCell(3).fill = sfill4;
// export excel var
buff = wb.xlsx.writeBuffer().then(function (data) {
var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}); saveAs(blob, "publications.xlsx");
});
반응형