如何使用Ajax显示PHPexcel的实时记录数?

时间:2018-03-12 09:19:06

标签: php jquery ajax phpexcel

我想使用PHPexcelAjax在前端显示实时记录计数。我这样做是通过创建JSON文件并将数据存储到此。我可以有更好的选择在HTML中显示记录数吗?它花了很多时间作为JSON文件打开和关闭这么多次。与此同时,我正在请求此JSON并在前端显示数据。我正在使用此代码并与您分享。请让我知道我可以有更好的选择。

文件名:Index.html

<div class="container">
        <div class="row">
            <h3>jQuery Ajax file upload with percentage progress bar</h3>
            <form id="myform" method="post">
                <div class="form-group">
                    <label>Select file: </label>
                    <input class="form-control" type="file" id="myfile" />
                </div>
                <div class="form-group">
                    <!--<div class="progress">
                        <div class="progress-bar progress-bar-success myprogress" role="progressbar" style="width:0%">0%</div>
                    </div>-->

                    <div class="msg"></div>
                    <div class="progress">
                        <div class="progress-bar progress-bar-success progress-bar-striped active" id="progressbar" role="progressbar" style="width:0%">0%</div>
                    </div>

                    <h2 id="records"></h2>
                    <h2 id="consist"></h2>
                    <h2 id="hsn"></h2>

                </div>

                <input type="button" id="btn" class="btn-success" value="Upload" />
            </form>
        </div>
    </div>

<script>
      $(function () {
            $('#btn').click(function () {
                $('.myprogress').css('width', '0');
                $('.msg').text('');
                var filename = $('#filename').val();
                var myfile = $('#myfile').val();
                if (filename == '' || myfile == '') {
                    alert('Please enter file name and select file');
                    return;
                }
                var formData = new FormData();
                formData.append('myfile', $('#myfile')[0].files[0]);
                formData.append('filename', filename);
                $('#btn').attr('disabled', 'disabled');
               // $('.msg').text('Uploading in progress...');
                $.ajax({
                    url: 'uploadscript.php',
                    data: formData,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    /*
                    xhr: function () {
                        var xhr = new window.XMLHttpRequest();  
                        xhr.upload.addEventListener("progress", function (evt) {
                            if (evt.lengthComputable) {
                                var percentComplete = evt.loaded / evt.total;
                                percentComplete = parseInt(percentComplete * 100);
                                $('.myprogress').text(percentComplete + '%');
                                $('.myprogress').css('width', percentComplete + '%');
                            }
                        }, false);
                        return xhr;
                    },*/
                    success: function (data) {
                        console.log(data);
                        var myData = JSON.parse(data);
                        console.log(myData.records.length);
                        $('#records').text("Records Found : " + myData.records.length).show();
                        $('#consist').text("Consistency : " + (myData.records.length - myData.notConsist.length)).show();
                        //$('.msg').text(data);
                        $('.msg').html(`<div class="alert alert-success"><strong>Success!</strong> Upload successfully!</div>`);
                        $('#btn').removeAttr('disabled');
                        $('.progress').hide();
                    }
                });   
                t = setTimeout("updateStatus()", 3000);
            });
        });

        function updateStatus(){ 
          $.getJSON('upload/my.json', function(data){      
                               var items = []; 

                               pbvalue = 0; 
                               var notExistHSN = 0;
                               var consistency = 0;
                               var notConsist = 0;
                               if(data){ 

                                    var total = data['total']; 

                                    var current = data['current'];  




                                    console.log(current);

                                    var pbvalue = Math.floor((current / total) * 100);  

                                    if(pbvalue>0){   

                                    $('#progressbar').text(pbvalue + '%');
                                    $('#progressbar').css('width', pbvalue + '%');
                                        //console.log(pbvalue);  
                                    }  
                                    $('#records').text("Records Found : " + current).show();


                                }  
                                if(pbvalue < 100){  

                                   t = setTimeout("updateStatus()", 3000);  

                                }  
          }).fail(function() {t = setTimeout("updateStatus()", 3000)});  
        } 
    </script>

文件名:uploadscript.php

<?php 
error_reporting(E_ERROR | E_PARSE);
$target_dir = 'upload/';
$target_file = $target_dir . basename($_FILES["myfile"]["name"]);


$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

move_uploaded_file($_FILES["myfile"]["tmp_name"], $target_file);

require('Classes/PHPExcel.php');
require_once "Classes/PHPExcel/IOFactory.php";
$path = $target_file;
$fileObj = PHPExcel_IOFactory::load( $path );
$sheetObj = $fileObj->getActiveSheet();


$startFrom = 1; //default value is 1
$limit =null;
$header=array();
foreach( $sheetObj->getRowIterator($startFrom, $limit) as $row ){

foreach( $row->getCellIterator() as $cell ){
    $value = $cell->getCalculatedValue(); 
    array_push($header,$value);
}
break;
}

$highestRow = $sheetObj->getHighestRow();

$arr = array('total'=>($highestRow-1), 'current'=>'0', 'notConsist'=>'0', 
'hsn'=>'0');

file_put_contents("upload/my.json",json_encode($arr));

$startFrom = 2; 
$limit =count($header);
$i=1;
$outp = "";
foreach( $sheetObj->getRowIterator($startFrom, $limit) as $row ){
if ($outp != "") {$outp .= ",";}
foreach( $row->getCellIterator() as $key=>$cell){
    // get all total count
    $arr['current'] = "$i"; 
    file_put_contents("upload/my.json",json_encode($arr));
    $value = $cell->getCalculatedValue();
    if($key==0){$outp .= '{"'.$header[$key].'":"'. $value. '",';}
    else
    if($key==($limit-1)){$outp .= '"'.$header[$key].'":"'. $value. '"}';

    }
    else {        
    $outp .= '"'.$header[$key].'":"'. $value. '",';
    }
  }
  $i++;
 }
 $outp ='{"records":['.$outp.']}';
 echo $outp;

&GT;

0 个答案:

没有答案