웹 개발/React
[React] 엑셀 다운로드 xlsx
헤일리_HJ
2022. 9. 27. 11:22
1. xlsx 설치
yarn add xlsx
2. 엑셀 파일 다운로드 구현
import * as XLSX from "xlsx";
const ExcelDownload = () => {
...
// 다운로드 할 엑셀 데이터
const [excelDownloadData, setExcelDownloadData] = useState({});
// API를 통해 다운로드 할 엑셀 데이터를 받아온다. [React-Query]
const onSuccessGetExcelData = (data) => {
setExcelDownloadData(data.excelData);
};
const onErrorGetExcelData = (error) => {
console.log(error);
};
const { refetch: getExcelData } = useExcelDataDownload(
onSuccessGetExcelData,
onErrorGetExcelData
);
// 다운로드 버튼을 눌렀을 때 동작한다.
const excelDownload = () => {
if (excelDownloadData) {
const dataWS = XLSX.utils.json_to_sheet(excelDownloadData);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, dataWS, "data");
XLSX.writeFile(wb, "예제_엑셀다운로드.xlsx");
}
};
...
}
export default ExcelDownload;