JSON数据到React Table

时间:2019-05-03 10:33:55

标签: json reactjs

我正在读取Excel文件作为json对象。

这是我的Excel文件。

enter image description here

我正在如下检查工具中将excel数据作为json对象读取。

enter image description here

我需要将这些json对象传递到一个可以逐行选择的反应表中。

enter image description here

有什么方法可以做到吗?

4 个答案:

答案 0 :(得分:0)

要遍历对象,您可以这样做,

const data = Object.keys(obj).forEach(function(key,index) {
    // key: the name of the object key
    // index: the ordinal position of the key within the object 
    return (<tr><td>{obj[key]}</td>... //create td's as per your data</tr>)
});

在您的组件中。

<Table>
   {data}
</Table>

答案 1 :(得分:0)

表组件:

import React, { Component } from 'react';

export class Table extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selected: []
    }; // for future

    this.checkbox = React.createRef();

    this.handleSelectAll = this.handleSelectAll.bind(this);
    this.handleSelect = this.handleSelect.bind(this);
    this.dispatchSelect = this.dispatchSelect.bind(this);
  }

  handleSelectAll() {
    const { metaData } = this.props;
    const { selectable } = metaData;

    if (selectable) {
      const { data } = this.props;
      const { selected } = this.state;

      if (selected.length === data.length) {
        return this.setState({
          selected: []
        }, this.dispatchSelect);
      }

      return this.setState({
        selected: data
      }, this.dispatchSelect);
    }
  }

  handleSelect(event) {
    const target = event.currentTarget || event.target;

    const { metaData } = this.props;
    const { selectable } = metaData;

    if (selectable) {
      const index = +target.dataset.index;
      const { data } = this.props;
      const item = data[index];
      const { selected } = this.state;

      if (selected.some(select => select === item)) {
        return this.setState({
          selected: selected.filter(select => select !== item)
        }, this.dispatchSelect);
      }

      return this.setState({
        selected: selected.concat(item)
      }, this.dispatchSelect);
    }
  }

  dispatchSelect() {
    const { data } = this.props;
    const { selected } = this.state;
    const length = selected.length;

    if (length < data.length && length > 0) {
      this.checkbox.current.indeterminate = true;
    } else {
      this.checkbox.current.indeterminate = false;
    }

    this.props.metaData.selectable.onChange(this.state.selected);
  }

  render() {
    return (
      <table>
        <thead>
        {this.header}
        </thead>
        <tbody>
        {this.body}
        </tbody>
      </table>
    );
  }

  get header() {
    const { metaData, data } = this.props;
    const { selectable, columns } = metaData;
    const { selected } = this.state;

    return (
      <tr className="table-header">
        {
          selectable && <td>
            <input ref={this.checkbox}
                   type="checkbox"
                   onClick={this.handleSelectAll}
                   checked={selected.length === data.length}
                   readOnly
            />
          </td>
        }
        {
          columns.map((item, key) => (
            <td key={key}>
              {item.label}
            </td>
          ))
        }
      </tr>
    );
  }

  get body() {
    const { metaData, data } = this.props;
    const { selectable, columns } = metaData;
    const { selected } = this.state;

    return data.map((item, key) => (
      <tr key={key}>
        {
          selectable && <td>
            <input type="checkbox"
                   checked={selected.some(select => select === item)}
                   onClick={this.handleSelect}
                   data-index={key}
                   readOnly
            />
          </td>
        }

        {
          columns.map((column, key) => {
            const { dataPath, renderer } = column;
            const value = item[dataPath];

            if (renderer && typeof renderer === 'function') {
              return (
                <td key={key}>
                  {renderer(value, item, column)}
                </td>
              );
            }

            return (
              <td key={key}>
                {value}
              </td>
            );
          })
        }
      </tr>
    ));
  }
}

示例:

import { Table } from '...';

...
render() {
  const { data } = this.state;
  const metaData = {
    selectable: {
      onChange: selected => console.log(selected)
    },
    columns: [
      {
        label: 'User ID',
        dataPath: 'USER ID'
      },
      {
        label: 'Serial No',
        dataPath: 'SERIAL NO'
      },
      {
        label: 'Status',
        dataPath: 'STATUS',
        renderer: value => {
          if (value) {
            if (value === 'T') {
              return (
                <span className="badge-success">Success</span>
              );
            }

            if (value === 'F') {
              return (
                <span className="badge-danger">Failed</span>
              );
            }
          }

          return null;
        }
      }
    ]
  }

  return (
    <Table metaData={metaData} data={data}/>
  );
}
...

CodeSandbox:https://codesandbox.io/embed/my0r24pr5p

答案 2 :(得分:0)

由于excel数据显示在检查工具中,因此我们可以将数据设置为状态并直接在表中调用它们。

 handleFiles = event => {
    var fileType = "xlsx";

    if (event.target.files && event.target.files[0]) {
      var extension = event.target.files[0].name
          .split(".")
          .pop()
          .toLowerCase(), //file extension from input file
        isSuccess = fileType.indexOf(extension) > -1; //is extension in acceptable types

      if (isSuccess) {
        //yes
        var reader = new FileReader();

        reader.onload = event => {
          alert("Valid File extension");

          const bstr = event.target.result;

          const wb = XLSX.read(bstr, { type: "binary" });

          console.log("data>>>", wb);
          /* Get first worksheet */
          const wsname = wb.SheetNames[0];
          const ws = wb.Sheets[wsname];
          /* Convert array of arrays */

          const data = XLSX.utils.sheet_to_json(ws);

          //set  data into 
          this.setState({
            data: XLSX.utils.sheet_to_json(ws)
          });
          // ws;
          // { header: 1 }
          // );
          /* Update state */

          console.log("Data>>>", data);
        };
        reader.readAsBinaryString(event.target.files[0]);
      } else {
        //no
        alert("Invalid File Type ");
      }
    }
  };

在表中应按如下所示对其进行更新。

 <CheckboxTable 
     .............
                data={this.state.data}
      ........
    />

答案 3 :(得分:-1)

创建一个后端API来提供数据!并使用Axios或Fetch进行GET请求。