在React项目中下载JSON文件和CSV文件


一些网站允许用户在web应用中将表格数据导出并以JSONCSV格式下载它们。

准备工作

  1. NodeJS环境
  2. 快速创建React工程:
    npm init vite@latest download_csv_json_file --template react
  3. 进入工程:cd download_csv_json_file
    安装依赖: npm install
    运行项目:npm run dev
    查看项目:浏览器打开地址:http://localhost:3000,可以看到默认的工程页面。

具体实现

  1. 在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": "¥"
        }
      ]
    }
  2. 修改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
  3. 修改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;
    }
  4. 查看页面:http://localhost:3000

文章作者: XiaoSenMao
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 XiaoSenMao !
  目录