반응형
1. exceljs 를 받는다.
npm install exceljs
2. controller 에 작성한다.
this is controller.ts
import { Res, Req, Get } from '@nestjs/common';
import * as ExcelJS from 'exceljs';
...
// 엑셀 다운로드
@Get('downloadExcel')
async downloadExcel(
@Req() req : Request
, @Res() res : Response ) {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('TestExportXLS');
worksheet.columns = [
{ header: 'name', key: 'name' },
{ header: 'age', key: 'age' }
];
worksheet.addRow({
name: 'test Row',
age: 37
});
const buffer = await workbook.xlsx.writeBuffer();
res.header('Content-Disposition', 'attachment; filename=data.xlsx');
res.type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.send(buffer);
}
3. html
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
.....
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
.....
</head>
<body>
...
<button type="button" id="download_excel">엑셀다운로드</button>
...
</body>
<script>
// 엑셀 다운로드 버튼 클릭
$("#download_excel").click(function () {
axios({
method: "get",
url: "/downloadExcel",
responseType: "blob",
})
.then((response) => {
const url = window.URL.createObjectURL(
new Blob([response.data])
);
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "data.xlsx");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
})
.catch((error) => {
});
});
</script>
반응형
'Programming > Node.js' 카테고리의 다른 글
[NestJS] read excel file With exceljs (DiskStorage) (0) | 2024.12.06 |
---|---|
[NestJS] Image file download with Url (0) | 2024.12.06 |
[NestJS] Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client (0) | 2024.12.02 |
[NestJS] Handlebars template in hbs(Handlebars) (0) | 2024.11.26 |
[NestJS] Table leftJoin with Mysql2 (0) | 2024.11.24 |