一些网站允许用户在web应用中将表格数据导出并以JSON和CSV格式下载它们。
准备工作
- NodeJS环境
- 快速创建React工程:
npm init vite@latest download_csv_json_file --template react
- 进入工程:
cd download_csv_json_file
安装依赖:npm install
运行项目:npm run dev
查看项目:浏览器打开地址:http://localhost:3000,可以看到默认的工程页面。
具体实现
- 在src目录下新建
fruits.json
文件,写入以下内容:{ "fruits": [ { "id": 0, "name": "Apple", "price": 8, "currency": "¥" }, { "id": 1, "name": "Banana", "price": 10, "currency": "¥" }, { "id": 2, "name": "Grapes", "price": 6, "currency": "¥" }, { "id": 3, "name": "Mango", "price": 12, "currency": "¥" } ] }
- 修改
App.jsx
文件内容:import React from 'react' import './App.css' import fruitsData from './fruits.json' const downloadFile = ({ data, fileName, fileType }) => { const blob = new Blob([data], { type: fileType }) const a = document.createElement('a') a.download = fileName a.href = window.URL.createObjectURL(blob) const clickEvt = new MouseEvent('click', { view: window, bubbles: true, cancelable: true, }) a.dispatchEvent(clickEvt) a.remove() } const exportToJson = e => { e.preventDefault() downloadFile({ data: JSON.stringify(fruitsData.fruits), fileName: 'fruits.json', fileType: 'text/json', }) } const exportToCsv = e => { e.preventDefault() let headers = ['Id, Name, Price, Currency'] // 将数据转换为csv格式 let fruitsCsv = fruitsData.fruits.reduce((acc, fruit) => { const { id, name, price, currency } = fruit acc.push([id, name, price, currency].join(',')) return acc }, []) downloadFile({ data: [...headers, ...fruitsCsv].join('\n'), fileName: 'users.csv', fileType: 'text/csv', }) } function App() { return ( <div className='App'> <h1>在React项目中下载JSON和CSV文件</h1> <table className='fruitsTable'> <thead> <tr> <th>ID</th> <th>Name</th> <th>Price</th> <th>Currency</th> </tr> </thead> <tbody> {fruitsData.fruits.map(fruit => { const { id, name, price, currency } = fruit return ( <tr key={id}> <td>{id}</td> <td>{name}</td> <td>{price}</td> <td>{currency}</td> </tr> ) })} </tbody> </table> <div className='actionBtns'> <button type='button' onClick={exportToJson}> Export to JSON </button> <button type='button' onClick={exportToCsv}> Export to CSV </button> </div> </div> ) } export default App
- 修改
App.css
文件:.App { max-width: 60rem; margin: 2rem auto; } .fruitsTable th, .fruitsTable td { padding: 0.4rem 0.6rem; text-align: left; } .actionBtns { margin-top: 1rem; } .actionBtns button + button { margin-left: 1rem; }
- 查看页面:http://localhost:3000