react中导出、导入excel

react中前段Excel的导入导出

前端Excel的导出

  • 前端使用xlsx

  • import React, { useState, useEffect} from ‘react‘;
    import { Table, Tag, Space } from ‘antd‘;
    import XLSX from "xlsx";
    
    const Xlsx = ({...props}) =>{
    
        const [columns, setColumns] = useState([
            {
              title: ‘Name‘,
              dataIndex: ‘name‘,
              key: ‘name‘,
              render: text => <a>{text}</a>,
            },
            {
              title: ‘Age‘,
              dataIndex: ‘age‘,
              key: ‘age‘,
              render: ()=> ‘xxx‘
            },
            {
              title: ‘Address‘,
              dataIndex: ‘address‘,
              key: ‘address‘,
            },
            {
              title: ‘Tags‘,
              key: ‘tags‘,
              dataIndex: ‘tags‘,
              render: tags => (
                <>
                  {tags.map(tag => {
                    let color = tag.length > 5 ? ‘geekblue‘ : ‘green‘;
                    if (tag === ‘loser‘) {
                      color = ‘volcano‘;
                    }
                    return (
                      <Tag color={color} key={tag}>
                        {tag.toUpperCase()}
                      </Tag>
                    );
                  })}
                </>
              ),
            },
            {
              title: ‘Action‘,
              key: ‘action‘,
              render: (text, record) => (
                <Space size="middle">
                  <a>Invite {record.name}</a>
                  <a>Delete</a>
                </Space>
              ),
            },
        ]);
        const [data, setData] = useState([
            {
              key: ‘1‘,
              name: ‘John Brown‘,
              age: 32,
              address: ‘New York No. 1 Lake Park‘,
              tags: [‘nice‘, ‘developer‘],
            },
            {
              key: ‘2‘,
              name: ‘Jim Green‘,
              age: 42,
              address: ‘London No. 1 Lake Park‘,
              tags: [‘loser‘],
            },
            {
              key: ‘3‘,
              name: ‘Joe Black‘,
              age: 32,
              address: ‘Sidney No. 1 Lake Park‘,
              tags: [‘cool‘, ‘teacher‘],
            },
        ]);
    
        useEffect(()=>{
            console.log(‘初次进入‘);
        },[]);
    
        const exportExcle = () =>{
            var elt = document.getElementsByTagName(‘table‘)[0];
            console.log(elt)
            // 将表格的dom 元素转化为 excel工作薄
            var wb = XLSX.utils.table_to_book(elt, {sheet:"Sheet JS"});
            // 将工作薄导出为excel文件
            XLSX.writeFile(wb,‘导出.xlsx‘);
        }
    
        const onImportExcel = file => {
            // 获取上传的文件对象
            const { files } = file.target;
            // 通过FileReader对象读取文件
            const fileReader = new FileReader();
            fileReader.onload = event => {
              try {
                const { result } = event.target;
                // 以二进制流方式读取得到整份excel表格对象
                const workbook = XLSX.read(result, { type: ‘binary‘ });
                let data = []; // 存储获取到的数据
                // 遍历每张工作表进行读取(这里默认只读取第一张表)
                for (const sheet in workbook.Sheets) {
                  if (workbook.Sheets.hasOwnProperty(sheet)) {
                    // 利用 sheet_to_json 方法将 excel 转成 json 数据
                    data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                    // break; // 如果只取第一张表,就取消注释这行
                  }
                }
                console.log(data);
              } catch (e) {
                // 这里可以抛出文件类型错误不正确的相关提示
                console.log(‘文件类型不正确‘);
                return;
              }
            };
            // 以二进制方式打开文件
            fileReader.readAsBinaryString(files[0]);
          }
    
        return (
            <div>
                <button onClick={exportExcle}>
                    导出
                </button>
                <input type=‘file‘ accept=‘.xlsx, .xls‘ onChange={onImportExcel} />
                <Table className=‘table‘ columns={columns} dataSource={data} />
            </div>
        )
    }
    
    export default Xlsx;
    
  • 后端实现

  • export const downloadFile = (content, fileName) => {
      const blob = new Blob([content]);
      const downloadLink = document.createElement(‘a‘);
      downloadLink.download = fileName;
      downloadLink.style.display = ‘none‘;
      downloadLink.href = URL.createObjectURL(blob);
      document.body.appendChild(downloadLink);
      downloadLink.click();
      URL.revokeObjectURL(downloadLink);
      document.body.removeChild(downloadLink);
    };
    

react中导出、导入excel

上一篇:类切换练习(更换盒子的类达到动画效果)


下一篇:ARC124 B - XOR Matching 2(思维)