如何使用asp.net和angularJS将Excel文件导入数据库中的多个表?

时间:2018-06-20 09:09:23

标签: asp.net angularjs asp.net-web-api

我已经开发了一个应用程序,并且在此应用程序中,我想将文件Excel导入数据库中的多个表,并且由于我是angularJS和.NET的初学者,因此我使用.net Web api和angularjs,并且开发一个功能,当我将数据导入到一个单表中时,它可以工作,但是如何将数据导入到DB中的3个表中的问题! 。并且这3个表相互链接(在我的示例代码中,有2个表CandidatureCandidat)。我的问题是:如何将Excel文件导入数据库中的多个表,谢谢。 (我使用asp.net Web API和angularJS)

controller.cs:

/////
 [Route("api/Candidature/SaveData")]
        [HttpPost]
        [ResponseType(typeof(Candidat))]
        public IHttpActionResult SaveData(List<Candidature> Candidatures, List<Candidat> candidat)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            foreach (var data in Candidatures)
            {
                db.Candidature.Add(data);
            }
            db.SaveChanges();

            foreach (var data in candidat)
            {
                db.Candidat.Add(data);
            }

            db.SaveChanges();

            return StatusCode(HttpStatusCode.OK);

////

service.js:

 SaveData: {
                method: 'POST' ,
                url: serviceBase + 'Candidature/SaveData',
                isArray: true,
                headers: {
                    'Content-Type' : 'application/json'
                }
            },

CandidatureCtrl.js:

  $scope.Importation = function (data) {
                $scope.SelectedFileForUpload = null;
                $scope.UploadFile = function (files) {
                    $scope.$apply(function () { //I have used $scope.$apply because I will call this function from File input type control which is not supported 2 way binding
                        $scope.Message = "";
                        $scope.SelectedFileForUpload = files[0];
                    })
                };
                //Parse Excel Data
                $scope.ParseExcelDataAndSave = function () {
                    var file = $scope.SelectedFileForUpload;
                    if (file) {
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            var data = e.target.result;
                            //XLSX from js-xlsx library , which I will add in page view page
                            var workbook = XLSX.read(e.target.result, { type: 'binary', cellDates:true, cellStyles:true });
                            var sheetName = workbook.SheetNames[0];
                            var excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
                            if (excelData.length > 0) {
                                //Save data
                                Candidature.SaveData(excelData).then(function (data) {
                                    if (data.status) {
                                        $scope.Message = excelData.length + " record inserted";
                                    }
                                    else {
                                        $scope.Message = "Failed";
                                    }
                                }, function (error) {
                                    $scope.Message = "Error";
                                });
                                // Candidature.SaveDatacandidature(excelData).then(function (data) {
                                //     if (data.status) {
                                //         $scope.Message = excelData.length + " record inserted";
                                //     }
                                //     else {
                                //         $scope.Message = "Failed";
                                //     }
                                // }, function (error) {
                                //     $scope.Message = "Error";
                                // });
                               // $scope.SaveData(excelData);
                            }
                            else {
                                $scope.Message = "No data found";
                            }
                        }
                        reader.onerror = function (ex) {
                            console.log(ex);
                        }
                        reader.readAsBinaryString(file);
                    }
                };
                var dialogOpts = {
                    backdrop: 'static',
                    keyboard: false,
                    scope: $scope,
                    size: 'lg',
                    templateUrl: 'views/candidature/Importation.html',
                    controller: ['$scope', '$uibModalInstance','$sce',
                        function ($scope, $uibModalInstance, $sce) {

                            $scope.cancel = function () {
                                $uibModalInstance.dismiss('cancel');
                            };
                        }
                    ]
                };
                $uibModal.open(dialogOpts);

            };

Importation.html:

  <!DOCTYPE html>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"  rel="stylesheet"/>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.1/xlsx.full.min.js"></script>
        <script src="http://oss.sheetjs.com/js-xlsx/jszip.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
        <!--<script src="app/views/candidature/candidatureCtrl.js"></script>-->
    </head>
    <body ng-app="agu">
    <div ng-controller="candidatureCtrl" class="container" style="margin-top:50px;">
        <div class="form-inline">
            <input type="file" name="file" class="form-control"
                   onchange="angular.element(this).scope().UploadFile(this.files)"/>
            <input type="button" value="Import" class="btn btn-success"  ng-disabled="!SelectedFileForUpload"
                   ng-click="ParseExcelDataAndSave()" />
            <br/>
            <span style="color:red">
                {{Message}}
            </span>
        </div>
    </div>
    </body>
    </html>

1 个答案:

答案 0 :(得分:0)

在您的Web API中,您期望Candidaturescandidat有两个数组。

但是从您的控制器中,您只传递了一组数据excelData

因此,对于api来说,它不会执行此代码,

foreach (var data in candidat) 
{
    db.Candidat.Add(data); 
}

因为候选人nullundefined。因此,它不会经历以下代码永远不会执行的循环。

  

db.Candidat.Add(data);