React를 사용하여 Api에서 Excel로 데이터를 내보내는 방법(맞춤 헤더 포함)
In my , about exporting data to Excel from api using React, there were comments like how to add custom header and style to the sheet!?. So considering these comments, in this post I decided to show solution for first issue which is adding custom headers to your Excel sheet.
이 게시물에서는 사용자 지정 헤더를 추가하는 두 가지 방법이 표시됩니다.
첫 번째 방법
설정
새 프로젝트 만들기
npx create-react-app react-data-to-excel
로컬에서 프로젝트 실행
npm start

다음 단계로 넘어가겠습니다.
라이브러리 설치
이 프로젝트의 경우 다음 라이브러리를 설치해야 합니다.
npm install xlsx file-saver axios
xlsx - 다양한 스프레드시트 형식을 구문 분석하고 작성하기 위한 라이브러리
file-saver - 클라이언트 측에 파일을 저장하기 위한 라이브러리
axios - 브라우저 및 node.js용 약속 기반 HTTP 클라이언트. 서버에서 데이터를 가져오는 데 사용합니다.
구성품
프로젝트 내에서 구성 요소 생성ExportToExcel.js
import React from 'react'
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";
export const ExportToExcel = ({ apiData, fileName }) => {
const fileType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
const fileExtension = ".xlsx";
const exportToCSV = (apiData, fileName) => {
const ws = XLSX.utils.json_to_sheet(apiData);
const wb = { Sheets: { data: ws }, SheetNames: ["data"] };
const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const data = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data, fileName + fileExtension);
};
return (
<button onClick={(e) => exportToCSV(apiData, fileName)}>Export</button>
);
};
업데이트App.js
import React from 'react'
import axios from 'axios'
import './App.css';
import {ExportToExcel} from './ExportToExcel'
function App() {
const [data, setData] = React.useState([])
const fileName = "myfile"; // here enter filename for your excel file
React.useEffect(() => {
const fetchData = () =>{
axios.get('https://jsonplaceholder.typicode.com/posts').then(postData => {
// reshaping the array
const customHeadings = postData.data.map(item=>({
"Article Id": item.id,
"Article Title": item.title
}))
setData(customHeadings)
})
}
fetchData()
}, [])
return (
<div className="App">
<ExportToExcel apiData={data} fileName={fileName} />
</div>
);
}
export default App;
official SheetJS CE docs에 따르면 . 기본적으로 json_to_sheet
는 머리글 행이 있는 워크시트를 만듭니다.
헤더를 추가하는 이 방법은 필요에 따라 배열을 객체로 재구성하는 것입니다. Excel 파일의 헤더는 우리가 정의한 객체 키에서 오기 때문입니다.
우리의 경우 헤더는 "기사 ID"와 "기사 제목"입니다.
프로젝트 실행
npm start

프로젝트가 성공적으로 시작되면 버튼을 클릭하여 Excel 파일을 다운로드합니다.

결과

두 번째 방법
배열 내부를 재구성할 필요가 없습니다App.js
. 이 코드를 추가하기만 하면 됩니다.
XLSX.utils.sheet_add_aoa(ws, [["Name", "Birthday", "Age", "City"]], { origin: "A1" });
ExportToExcel.js
파일 내부
const exportToCSV = (apiData, fileName) => {
const ws = XLSX.utils.json_to_sheet(apiData);
/* custom headers */
XLSX.utils.sheet_add_aoa(ws, [["Name", "Birthday", "Age", "City"]], { origin: "A1" });
const wb = { Sheets: { data: ws }, SheetNames: ["data"] };
const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const data = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data, fileName + fileExtension);
};
결과

소스 코드 링크
1st way
2nd way
Reference
이 문제에 관하여(React를 사용하여 Api에서 Excel로 데이터를 내보내는 방법(맞춤 헤더 포함)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/jasurkurbanov/how-to-export-data-to-excel-from-api-using-react-incl-custom-headers-5ded
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
npx create-react-app react-data-to-excel
npm start
npm install xlsx file-saver axios
import React from 'react'
import * as FileSaver from "file-saver";
import * as XLSX from "xlsx";
export const ExportToExcel = ({ apiData, fileName }) => {
const fileType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8";
const fileExtension = ".xlsx";
const exportToCSV = (apiData, fileName) => {
const ws = XLSX.utils.json_to_sheet(apiData);
const wb = { Sheets: { data: ws }, SheetNames: ["data"] };
const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const data = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data, fileName + fileExtension);
};
return (
<button onClick={(e) => exportToCSV(apiData, fileName)}>Export</button>
);
};
import React from 'react'
import axios from 'axios'
import './App.css';
import {ExportToExcel} from './ExportToExcel'
function App() {
const [data, setData] = React.useState([])
const fileName = "myfile"; // here enter filename for your excel file
React.useEffect(() => {
const fetchData = () =>{
axios.get('https://jsonplaceholder.typicode.com/posts').then(postData => {
// reshaping the array
const customHeadings = postData.data.map(item=>({
"Article Id": item.id,
"Article Title": item.title
}))
setData(customHeadings)
})
}
fetchData()
}, [])
return (
<div className="App">
<ExportToExcel apiData={data} fileName={fileName} />
</div>
);
}
export default App;
npm start
배열 내부를 재구성할 필요가 없습니다
App.js
. 이 코드를 추가하기만 하면 됩니다. XLSX.utils.sheet_add_aoa(ws, [["Name", "Birthday", "Age", "City"]], { origin: "A1" });
ExportToExcel.js
파일 내부 const exportToCSV = (apiData, fileName) => {
const ws = XLSX.utils.json_to_sheet(apiData);
/* custom headers */
XLSX.utils.sheet_add_aoa(ws, [["Name", "Birthday", "Age", "City"]], { origin: "A1" });
const wb = { Sheets: { data: ws }, SheetNames: ["data"] };
const excelBuffer = XLSX.write(wb, { bookType: "xlsx", type: "array" });
const data = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data, fileName + fileExtension);
};
결과

소스 코드 링크
1st way
2nd way
Reference
이 문제에 관하여(React를 사용하여 Api에서 Excel로 데이터를 내보내는 방법(맞춤 헤더 포함)), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/jasurkurbanov/how-to-export-data-to-excel-from-api-using-react-incl-custom-headers-5ded텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)