Notice
Recent Posts
Recent Comments
Link
반응형
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- useResetREcoilState()
- next excel down
- fe
- next csv append
- useSetRecoilState()
- next.js excel download
- react 파일명 깨짐
- Next.js
- useRecoilStateLoadable()
- selector()
- js 파일명 꺠짐
- react mac 파일명 깨짐
- React
- Cookie
- onpointertype
- Recoil 상태
- csv to excel
- next csv
- Typescript
- node.js csv
- 하단드로우
- useRecoilValue()
- react excel down
- next.js csv
- csv 파일 생성
- javascript
- atom()
- csv로 excel 다운로드하기
- csv 파일에 정보 추가
- useRecoilState()
Archives
- Today
- Total
나만의 개발 공간
CSV 파일을 Excel 파일로 변환해서 다운로드하기 본문
반응형
이전 글(CSV파일 생성)에서부터 이어지는 글입니다.
CSV파일로 다운로드하게끔 후 해당 파일을 Excel파일로 변환해서 다운로드 하게끔 코드를 작성해보겠습니다.
프론트 부분입니다.
이전 글에서 추가 된 부분만 작성했습니다.
"use client"; // 해당 부분을 작성하지 않으면 에러가 나옵니다!!
import { css } from "@emotion/css";
import axios from "axios";
import { useCallback, useState } from "react";
export default function Home() {
...
// 엑셀 다운로드
const onClickExcelDownload = useCallback(async () => {
try {
const response = await axios({
url: "/api/excel",
method: "get",
responseType: "blob", // 응답을 blob형태로
});
if (response.status === 200) {
// 해당 컴퓨터 시간말고 UTC시간으로 하기 위한 작업!
// 현재 시간
const currentTime = new Date();
// UTC 시간 계산
const utcTime =
currentTime.getTime() + currentTime.getTimezoneOffset() * 60 * 1000;
// UTC to KST (UTC + 9시간)
const KR_TIME_DIFF = 9 * 60 * 60 * 1000;
const krCurr = new Date(utcTime + KR_TIME_DIFF);
krCurr.setDate(krCurr.getDate());
const year = krCurr.getFullYear();
const month = ("0" + (krCurr.getMonth() + 1)).slice(-2);
const day = ("0" + krCurr.getDate()).slice(-2);
const hour = ("0" + krCurr.getHours()).slice(-2);
const minutes = ("0" + krCurr.getMinutes()).slice(-2);
const seconds = ("0" + krCurr.getSeconds()).slice(-2);
const nowDate = year + month + day + hour + minutes + seconds;
// Blokb객체를 사용하여 파일 다운로드 처리
const blob = response.data;
const link = document.createElement("a");
const url = window.URL.createObjectURL(blob); // Blob 데이터를 URL로 변환
link.href = url;
link.download = `csv_to_excel_${nowDate}.xlsx`;
link.click(); // 다운로드 시작
window.URL.revokeObjectURL(url); // URL 객체 메모리 해제
}
} catch (error) {
console.error(error);
}
}, []);
return (
<div>
<ul>
...
<li>
<button onClick={onClickExcelDownload}>엑셀 다운로드</button>
</li>
</ul>
</div>
);
}
서버 API 부분입니다.
해당 부분을 작성하시기 전에
xlsx-js-style을 다운로드 받아주시길 바랍니다.
https://www.npmjs.com/package/xlsx-js-style 에 접속하셔서 사용법을 익히시면 좋을 꺼 같습니다.
import { NextResponse } from "next/server";
import path from "path";
import { promises as fs } from "fs";
import xlsx from "xlsx-js-style";
export async function GET() {
try {
const fileName = "csv_test.csv";
const filePath = path.join(process.cwd(), "csv", fileName);
// 파일 존재를 확인합니다. csv_test.csv;
await fs.access(filePath);
const csvData = await fs.readFile(filePath, "utf8");
const wb = xlsx.utils.book_new();
const resultCsvData = csvData.split("\r\n").map((row) => row.split(","));
// 해당 부분은 xlsx-js-style 참고하시는 걸 추천드립니다!
const header = resultCsvData[0].map((v) => ({
v,
t: "s",
s: {
border: {
top: { style: "thin", color: { rgb: "#000000" } },
left: { style: "thin", color: { rgb: "#000000" } },
bottom: { style: "thin", color: { rgb: "#000000" } },
right: { style: "thin", color: { rgb: "#000000" } },
},
font: {
bold: true,
sz: 14,
color: { rgb: "FFFFFF" },
},
alignment: {
horizontal: "center",
},
fill: {
fgColor: { rgb: "000000" },
},
},
}));
let body = resultCsvData.slice(1).map((row) =>
row.map((v) => ({
v,
t: "s",
s: {
font: {
sz: 14,
},
alignment: {
horizontal: "center",
},
border: {
top: { style: "thin", color: { rgb: "#000000" } },
left: { style: "thin", color: { rgb: "#000000" } },
bottom: { style: "thin", color: { rgb: "#000000" } },
right: { style: "thin", color: { rgb: "#000000" } },
},
},
}))
);
body = body.filter((row) => row.some((cell) => cell.v.trim() !== ""));
const ws = xlsx.utils.aoa_to_sheet([header, ...body]);
ws["!cols"] = [
{ wch: 30 },
{ wch: 30 },
{ wch: 30 },
{ wch: 30 },
{ wch: 30 },
];
xlsx.utils.book_append_sheet(wb, ws, "엑셀 파일 다운로드 테스트 중");
const excelBuffer = xlsx.write(wb, { bookType: "xlsx", type: "buffer" });
// new Response를 사용해서 엑셀 파일을 buffer 형태로 응답하여 브라우저가 엑셀 파일로 인식하게 해여
// attachment로 설정하여 사용자가 파일을 다운로드하게 합니다
return new Response(excelBuffer, {
headers: {
"Content-Type":
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Content-Disposition": `attachment; filename="csv_test.xlsx"`,
},
});
} catch (error) {
console.error(error);
return NextResponse.json({
msg: "CSV 파일이 없습니다.",
});
}
}
해당 부분은 app/api/excel/route.ts로 작업하였습니다.
csv파일이 존재하지 않으면 Error로 인하여 엑셀다운로드를 생성하지 않고,
존재해야만 엑셀파일로 변환해서 다운로드 하게끔 됩니다.
엑셀 다운로드 버튼을 클릭해주세요.
해당 파일명은 현재 UTC시간으로 가져온 파일명으로 작업했기 떄문에 아래와 같이 나왔습니다.
(작성자는 mac - numbers로 보여집니다. excel이 없기 때문에 ㅠㅠㅠㅠ 그래도 잘 보입니다!!)
파일을 열어보게 되면 아래와 같이 기존에 등록했던 정보들이 나오게 됩니다.
기존 csv파일에 추가하여 엑셀로 다운로드 하시고 싶으시면 폼 정보를 입력하여 등록 후 엑셀 파일 다운로드 버튼 클릭하시면 됩니다.
이상으로 csv정보를 엑셀파일로 다운로드 하는 방법이였습니다.
제가 짠 코드는 참고용으로 봐주시고 수정해야할 부분이 있으시면 말씀해주시면 감사하겠습니다. 꾸벅꾸벅!~~
반응형
'Next.js' 카테고리의 다른 글
CSV 파일 생성 및 Append 하기 (0) | 2025.02.02 |
---|---|
next-i18next 다국어 지원 (0) | 2022.02.17 |
Comments