728x90
엑셀(xlsx) 파일과 csv의 차이
엑셀 파일 업로드 및 다운로드 기능을 구현하면서 csv라는 확장자를 처음 알게 되었다.
엑셀로 두 파일을 실행시켜 보니 같은 양식이었고 두 라이브러리의 차이점을 모르겠어서 찾아보았고 차이는 아래와 같다.
csv
1. 단순히 읽기, 쓰기 용도에 적합한 라이브러리이다.
2. 라이브러리가 가볍다.
3. 가벼운 만큼 기능이 제한적이다.
xlsx
1. 라이브러리에서 제공해주는 기능이 많다.
2. csv에 비해 라이브러리가 무겁다.
csv 를 사용해 코드를 작성한 후 xlsx 로도 작성해보니 확실히 csv를 사용하는 것이 간단하게 작성할 수 있어서 편했다.
구현하려는 기능을 파악한 후 사용할 라이브러리를 선택하면 될 것 같다.
CSV 사용
1. react-csv 라이브러리 설치
npm i react-csv
yarn add react-csv
typescript 사용 시 설치
npm i @types/react-csv
yarn add @types/react-csv
2. react-csv의 CSVLink를 사용한 코드 작성
import React, { useRef } from "react";
import { CSVLink } from "react-csv";
interface HeaderProps {
label: string;
key: string;
};
interface DataProps {
id: number;
name: string;
age: number;
};
const headers: HeaderProps[] = [
{ label: "id", key: "id" },
{ label: "이름", key: "name" },
{ label: "나이", key: "age" },
];
const data: DataProps[] = [
{ id: 1, name: "alice", age: 26 },
{ id: 2, name: "benny", age: 25 },
{ id: 3, name: "celen", age: 22 },
];
const App = () => {
const csvLink = useRef<CSVLink & HTMLAnchorElement & { link: HTMLAnchorElement }>(null);
const onClickExcelDownloadBtn = () => {
csvLink?.current?.link.click();
};
return (
<div>
<button onClick={onClickExcelDownloadBtn}>엑셀 다운로드</button>
<CSVLink
data={data}
headers={headers}
filename="학생부.csv"
style={{ display: hidden }}
ref={csvLink}
target="_blank"
/>
</div>
);
}
export default App;
xlsx 사용
1. xlsx, file-saver, read-excel-file 라이브러리 설치
npm i xlsx file-saver read-excel-file
yarn add xlsx file-saver read-excel-file
typescript 사용 시 설치
npm i @types/file-saver
yarn add @types/file-saver
2. 엑셀 파일 다운로드 코드
import React from "react";
import * as XLSX from "xlsx";
import * as FileSaver from "file-saver";
interface DataProps {
id: number;
name: string;
age: number;
};
const headers: string[] = ["ID", "이름", "나이"];
const data: DataProps[] = [
{ id: 1, name: "alice", age: 26 },
{ id: 2, name: "benny", age: 25 },
{ id: 3, name: "celen", age: 22 },
];
const App = () => {
const excelFileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
const excelFileName = "출석부";
const excelFileExtension = ".xlsx";
const onClickExcelDownloadBtn = async () => {
const ws = XLSX.utils.aoa_to_sheet([
["출석부"],
[""],
headers,
]);
data.map((data: DataProps) => {
XLSX.utils.sheet_add_aoa(ws, [[data.id, data.name, data.age]], {
origin: -1,
});
ws["!cols"] = [{ wpx: 100 }, { wpx: 100 }, { wpx: 100 }];
return false;
});
const wb = {
Sheets: { data: ws },
SheetNames: ["data"],
};
const excelButter = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const excelFile = new Blob([excelButter], { type: excelFileType });
await new Promise((resolve) => setTimeout(resolve, 1000));
FileSaver.saveAs(excelFile, excelFileName + excelFileExtension);
};
return (
<div>
<button onClick={onClickExcelDownloadBtn}>엑셀 다운로드</button>
</div>
);
}
export default App;
3. 엑셀 파일 업로드 코드
import React from "react";
import ReactXlsxFile from "read-excel-file";
interface DataProps {
id: number;
name: string;
age: number;
};
const headers: string[] = ["ID", "이름", "나이"];
const data: DataProps[] = [
{ id: 1, name: "alice", age: 26 },
{ id: 2, name: "benny", age: 25 },
{ id: 3, name: "celen", age: 22 },
];
const App = () => {
const onClickExcelUploadBtn = () => {
document.getElementById("xlsx-file-upload")?.click();
};
const onChangeXlsxFile = (e: ChangeEvent<HTMLInputElement> | any) => {
const file = e.target?.files[0];
if(
((file.name.substring(file.name.length-4, file.name.length)) === "xlsx") ||
((file.name.substring(file.name.length-3, file.name.length)) === "xls")
) {
ReactXlsxFile(file).then( async (results) => {
if(results[2][0] !== "ID" || results[2][1] !== "이름" || results[2][2] !== "나이") {
return alert("엑셀 양식이 올바르지 않습니다.");
}
console.log(results);
});
} else {
return alert(`xlsx 또는 xls 확장자의 파일만 선택가능합니다.\n\n현재 파일 : ${e.target?.files[0].name}`);
};
};
return (
<div>
<button onClick={onClickExcelUploadBtn}>엑셀 업로드</button>
<input
type="file"
id="xlsx-file-upload"
accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
onChange={(e) => onChangeExcelFile(e)}
/>
</div>
);
}
export default App;
참고 사이트
https://mingmeng030.tistory.com/268
https://kkhcode.tistory.com/12
https://gofogo.tistory.com/148
728x90
'🖥️Frontend > React' 카테고리의 다른 글
[React] zustand (0) | 2023.11.18 |
---|---|
[React] Redux & RTK (0) | 2023.11.17 |
[React] React 배포 시 CORS 이슈 (0) | 2023.09.13 |
[React] Inflearn 처음 만난 리엑트(React) - Context (0) | 2023.02.24 |
[React] Inflearn 처음 만난 리엑트(React) - Composition vs Inheritance (0) | 2023.02.24 |
댓글