【问题标题】:How to load json data into handsontable如何将json数据加载到handsontable中
【发布时间】:2016-09-19 06:42:20
【问题描述】:

我正在使用 sheetJs 从指令中的 csv/xls 文件中获取 json 数据。

myApp.directive("fileRead", [function () {
    return {
        scope: {
            data: '='
        },
        link: function ($scope, $elm, $attrs) {
            $elm.on('change', function (changeEvent) {
                var reader = new FileReader();

                reader.onload = function (evt) {
                    $scope.$apply(function () {
                        var data = evt.target.result;

                        var workbook = XLSX.read(data, {type: 'binary'});

                        var headerNames = XLSX.utils.sheet_to_json(
                                workbook.Sheets[workbook.SheetNames[0]],
                                {header: 1}
                        )[0];

                        console.log("headerNames: ", headerNames);

                        var data = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);

                        console.log("sheet2Json: " , data);

                        $scope.columnDefs = [];
                        headerNames.forEach(function (h) {
                            $scope.columnDefs.push({field: h});
                        });

                        $scope.data = data;
                        console.log("file 4: " , data);                             

                        $elm.val(null);
                    });
                };

                reader.readAsBinaryString(changeEvent.target.files[0]);
            });
        }
    };
}]);

以 json 格式检索的数据位于 $scope.data = data; 对象中。我在一个单独的 js 文件中有我的示例handsontable,如下所示:

var myData = [
    ["KK", 1234567890, "k.k999@gmail.com", "kvp@gmail.com"],
    ["KK", 1234567890, "k.k999@gmail.com", "kvp@gmail.com"],
    ["KK", 1234567890, "k.k999@gmail.com", "kvp@gmail.com"],
],
        container = document.querySelector('#exampleGrid');

var hot = new Handsontable(container, {
    data: myData,
    startRows: 5,
    startCols: 5,
    minSpareCols: 0,
    //always keep at least 1 spare row at the right
    minSpareRows: 0,
    //always keep at least 1 spare row at the bottom,
    rowHeaders: true,
    colHeaders: ['Name', 'Mobile number', 'Sender Email', 'Receiver Email'],
    contextMenu: true,
    width: 120,
    wordWrap: true
});

查看 Handsontable 文档,我看到了一种加载 json 数据的方法:

 hot.loadData(data.data);

现在我如何将 scope.data(jsondata) 加载到上述方法中,该方法位于单独的 js 文件中。我是否必须创建一个控制器并将数据传递给控制器​​范围?

HTML:

<div class="top-big-link">
    <file-read>
        <input id="csvFile" type="file" name="image" accept=".xls, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" title=" "/>
        <button id="csvFileImport" class="ImportFromExcelButton"><i class="fa fa-file-excel-o"> </i> Import from Excel</button>
    </file-read>
    <script>
        document.getElementById('csvFileImport').addEventListener('click', function () {
            document.getElementById('csvFile').click();

        });
    </script>
</div>

【问题讨论】:

    标签: javascript angularjs handsontable


    【解决方案1】:

    我不确定这是正确的做法,但它对我有用。

    通过此链接获得我的解决方案:Passing values from directive to controller

    感谢@Thomas Weglinski

    解决方案:

    将我的指令更改为双向绑定。

    myApp.directive("fileRead", [function () {
        return {
            scope: {
                fromDirectiveFn: '=method'
            },
        },
    
        function link(scope, element, attrs){
    
            $scope.data = data; //Json data reecieved from csv/xls file
            $scope.fromDirectiveFn($scope.data);
        }
    }
    

    并将我的 HTML 更改为以下内容:

    <file-read method="loadJson">
        <input id="csvFile" type="file" name="image" accept=".xls, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" title=" "/>
        <button id="csvFileImport" class="ImportFromExcelButton"><i class="fa fa-file-excel-o"> </i> Import from Excel</button>
    </file-read>
    

    这一行method="loadJson 调用控制器内部的函数并传递数据。

    【讨论】:

      【解决方案2】:

      // 对于 Angular

      //在component.html里面

      <hot-table [settings]="tableSettings" [data]="dataset" licenseKey= 'non-commercial-and-evaluation'></hot-table>
      

      //在component.ts里面

      tableSettings: any = {
          
          rowHeaders: true,
          // colHeaders: true,
          viewportColumnRenderingOffset: 27,
          viewportRowRenderingOffset: "auto",
          // colWidths: 150,
          // height: 500,
          // allowInsertColumn: false,
          // allowInsertRow: false,
          // allowRemoveColumn: false,
          // allowRemoveRow: false,
          // autoWrapRow: false,
          // autoWrapCol: false,
          // stretchH: "all",
          width: 3000,
          // autoWrapRow: true,
          //height: 487,
          // maxRows: 22,
          // manualRowResize: true,
          // manualColumnResize: true,
          // rowHeaders: true,
          
          colHeaders: [
            "Invoice_No",
            "Product_Description",
            "Receiver_Contact_Person_Name",
            "Receiver_Contact_Number",
            "Dropoff_Address",
            "Dropoff_Area",
            "Dropoff_City",
            "Unit_Price",
            "Number_of_Packages_in_Shipment",
            "Collection_Amount_for_delivered_Product",
            "Payment_Collection_Method",
            "Proof_Of_Delivery",
            "Shipment_Weight",
            "Shipment_Volume",
            "Pickup_Contact_Person_Name",
            "Pickup_Contact_Person_Number",
            "Pickup_Address",
            "Pickup_Area",
            "Pickup_City",
            "Comments"
          ],
          // manualRowMove: true,
          // manualColumnMove: true,
          // contextMenu: true,
          // filters: true,
          // dropdownMenu: true
        };
      
        dataset = [
          {
            Invoice_No: "ABCD1234",
            Product_Description: "XYZ",
            Receiver_Contact_Person_Name: "Jane Doe",
            Receiver_Contact_Number: "01700000001",
            Dropoff_Address: "DROPOFF_ADDRESS_1",
            Dropoff_Area: "Kawran Bazaar",
            Dropoff_City: "Dhaka",
            Unit_Price: 25,
            Number_of_Packages_in_Shipment: 2,
            Collection_Amount_for_delivered_Product: 50,
            Payment_Collection_Method: "PREPAID",
            Proof_Of_Delivery: "NONE",
            Shipment_Weight: 1,
            Shipment_Volume: 5,
            Pickup_Contact_Person_Name: "John Doe",
            Pickup_Contact_Person_Number: "01700000001",
            Pickup_Address: "PK_Address line",
            Pickup_Area: "Dhanmondi",
            Pickup_City: "Dhaka",
            Comments: "Comment"
          }
        ];
      

      【讨论】:

        猜你喜欢
        • 2016-03-22
        • 2016-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-11
        • 1970-01-01
        • 2017-01-05
        • 2012-11-03
        相关资源
        最近更新 更多