【问题标题】:Is there a way to load the headers from a CSV into a table to compare to the headers that are already in the system?有没有办法将 CSV 中的标头加载到表中以与系统中已有的标头进行比较?
【发布时间】:2019-06-10 15:26:10
【问题描述】:

我正在尝试加载两个 CSV 文件。一个是系统的标准,另一个是我们要导入的。我正在尝试创建一个表格,其中一侧显示标准,另一侧显示正在导入的 CSV 的下拉列表。显示标准并不太难,但在加载新的 CSV 文件时需要一些帮助,并且需要将新的 CSV 映射到标准,然后在正确的字段中创建一个包含信息的新文件。

这适用于 Javascript 和 ReactJS。我还没有找到一种方法来做到这一点,并希望得到一些帮助来解决这个问题。

import React, { Component } from 'react';
import Table from 'react-bootstrap/Table';
import ReactFileReader from 'react-file-reader';

export default class TableMap extends Component {
    state = {
        iGorMap: [


            {
                "FiduciaryOutsourcingField": "ID",
                "YourField": ""
            },
            {
                "FiduciaryOutsourcingField": "CreateDate",
                "YourField": ""
            },
            {
                "FiduciaryOutsourcingField": "UpdateDate",
                "YourField": ""
            },
            {
                "FiduciaryOutsourcingField": "RecordStatus",
                "YourField": ""
            },
            {
                "FiduciaryOutsourcingField": "Source",
                "YourField": ""
            },
            {
                "FiduciaryOutsourcingField": "SourceId",
                "YourField": ""
            },
            {
                "FiduciaryOutsourcingField": "BatchNumber",
                "YourField": ""
            },
            {
                "FiduciaryOutsourcingField": "CompletedStages",
                "YourField": ""
            },
            {
                "FiduciaryOutsourcingField": "EIN",
                "YourField": ""
            },
            {
                "FiduciaryOutsourcingField": "Location",
                "YourField": ""
            },

        ]
    }

    // renderSelectedDropdown() {
    //     return this.state.
    // }
    renderDropdownValues() {
        handleFiles = files => {
            var reader = new FileReader();
            reader.onload = e => {
                // Use reader.result
                this.setState({
                    csvData: reader.result
                });
            };
            reader.readAsText(files[0]);
            console.log(reader);
        };
        function convertJson(csvData) {
            var temp = csvData.split("\n");
            var temp2 = temp[0].split(",");
            return temp2;
        }

        var mappedFromCsv = convertJson(csvData);

        // var mappedFromCsv = Object.keys(this.state.temp2)
        //console.log(header)
        return mappedFromCsv.map((key, index) => {
            return <option value={index}>{key}</option>
            // return <th className="tableHeader" key={index}>{key}</th>
        })
    }
    renderTableData() {
        return this.state.iGorMap.map((iGorMap, index) => {
            const { FiduciaryOutsourcingField, YourField } = iGorMap 
            return (
                <tr key={FiduciaryOutsourcingField}>
                    <td>{FiduciaryOutsourcingField}</td>
                    <td>
                        <div className="dropdown" role="combobox" >
                            <select class="browser-default custom-select">
                                <option selected>Open this select menu</option>
                                {this.renderDropdownValues()}
                            </select>
                        </div>
                    </td>
                </tr >
            )
        })
    }
    renderTableHeader() {
        let header = Object.keys(this.state.iGorMap[0])
        return header.map((key, index) => {
            return <th className="tableHeader" key={index}>{key}</th>
        })
    }

    render() {
        return (
            <div>
                <ReactFileReader
                    multipleFiles={false}
                    fileTypes={[".csv"]}
                    handleFiles={this.handleFiles}
                >
                    <button type='button' className="btn btn-success">Upload</button>
                </ReactFileReader>
                <Table bordered hover striped>

                    <thead className="thead-dark" id="top">
                        {this.renderTableHeader()}
                    </thead>
                    <tbody>
                        {this.renderTableData()}
                    </tbody>
                </Table>
            </div>
        )
    }

};

【问题讨论】:

  • 抱歉,代码格式问题已尝试修复,但无法找到将其全部显示在代码屏幕中的方法。
  • 感谢@derpirscher 修复了我的代码示例。

标签: javascript arrays json reactjs csv


【解决方案1】:

我想通了。我需要创建状态,然后设置该状态。

import React, {
  Component
} from "react";
import Table from "react-bootstrap/Table";
import ReactFileReader from "react-file-reader";
import Papa from "papaparse";

export default class TableMap extends Component {
  constructor(props) {
    super(props);

    this.state = {
      //? standard Mapping for dataSet
      iGorMap: [{
          FiduciaryOutsourcingField: "ID",
          YourField: ""
        },
        {
          FiduciaryOutsourcingField: "CreateDate",
          YourField: ""
        },
        {
          FiduciaryOutsourcingField: "UpdateDate",
          YourField: ""
        },
        {
          FiduciaryOutsourcingField: "RecordStatus",
          YourField: ""
        }
      ],
      //*for options dropdown
      dropOpt: []
    };
  }

  //* This method gets the keys from dropOpt and then puts the key in each option in the dropdown
  renderDropdownValues() {
    return this.state.dropOpt.map((key, index) => {
      return ( <
        option key = {
          index
        }
        id = {
          index
        } > {
          key
        } <
        /option>
      );
    });
  }

  //* handleFiles transforms the incoming CSV sheet and returns the header from the first row
  handleFiles = files => {
    var reader = new FileReader();
    var parseConfig = {
      delimiter: "", // auto-detect
      newline: "", // auto-detect
      quoteChar: '"',
      escapeChar: '"',
      header: true,
      transformHeader: undefined,
      dynamicTyping: false,
      preview: 0,
      encoding: "",
      worker: false,
      comments: false,
      step: undefined,
      complete: undefined,
      error: undefined,
      download: false,
      skipEmptyLines: true,
      chunk: undefined,
      fastMode: undefined,
      beforeFirstChunk: undefined,
      withCredentials: undefined,
      transform: undefined,
      delimitersToGuess: [",", "\t", "|", ";", Papa.RECORD_SEP, Papa.UNIT_SEP]
    };

    //* All configuration options for "unparsing" JSON back to CSV
    //TODO: unparseConfig not currently used will need to use in full production.
    // var unparseConfig = {
    //   quotes: false, //or array of booleans
    //   quoteChar: '"',
    //   escapeChar: '"',
    //   delimiter: ",",
    //   header: true,
    //   newline: "\n",
    //   skipEmptyLines: true, //or 'greedy',
    //   columns: null //or array of strings
    // };

    //* reads incoming CSV file within the browser and parses the header of the first row
    reader.onload = e => {
      var fileIn = reader.result;
      var fileInParsed = fileIn.replace(/(00\/00\/0000)/g, ""); // Removing 00/00/00 dates
      var csvData = Papa.parse(fileInParsed, parseConfig);

      //* csvData.data is the grouping of Objects
      var dataJson = csvData.data;
      var jsonKeys = Object.keys(dataJson[0]);
      // console.log(dataJson[0]); //for debugging
      // console.log(csvData.data.length); //for debugging
      // console.log(jsonKeys); //for debugging

      //* breaks out the key and index of the jsonKeys array
      return jsonKeys.map((key, index) => {
        // console.log("I got here"); //for debugging
        // console.log(key, index); //for debugging
        return this.setState({
          dropOpt: jsonKeys
        });
      });
    };
    reader.readAsText(files[0]);
  };

  //* displays the data for the table
  renderTableData() {
    return this.state.iGorMap.map((key, index) => {
      const {
        FiduciaryOutsourcingField
      } = key; //destructuring
      return ( <
        tr key = {
          index
        } >
        <
        td key = {
          index
        }
        id = {
          index
        } > {
          FiduciaryOutsourcingField
        } <
        /td> <
        td >
        <
        div className = "dropdown"
        role = "combobox"
        aria - controls = "ex1-listbox"
        aria - expanded = "false" >
        <
        select className = "browser-default custom-select" > {
          this.renderDropdownValues()
        } <
        /select> <
        /div> <
        /td> <
        /tr>
      );
    });
  }
  renderTableHeader() {
    let header = Object.keys(this.state.iGorMap[0]);
    return header.map((key, index) => {
      return ( <
        th className = "tableHeader"
        key = {
          index
        } > {
          key
        } <
        /th>
      );
    });
  }

  render() {
    return ( <
      div >
      <
      ReactFileReader multipleFiles = {
        false
      }
      fileTypes = {
        [".csv"]
      }
      handleFiles = {
        this.handleFiles
      } >
      <
      button type = "button"
      className = "btn btn-success" >
      Upload <
      /button> <
      /ReactFileReader> <
      Table bordered hover striped >
      <
      thead className = "thead-dark"
      id = "top" >
      <
      tr > {
        this.renderTableHeader()
      } < /tr> <
      /thead> <
      tbody > {
        this.renderTableData()
      } < /tbody> <
      /Table> <
      /div>
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 2016-06-11
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多