importexcel.blade.php 8.54 KB
<?php
ini_set("precision", 15);

include_once app_path() . '/lib/phpexcel/PHPExcel.php';
if (isset($format) && $format == 'dataUpload') {
    if (isset($format) && $format == 'dataUpload') {
        $dataColumns = ['username' => 'Username', 'phone' => 'Phone', 'sessiontype' => 'webrtc/mobile',];
        $PHPExcelObj = new PHPExcel();
        $head        = 0;
        foreach ($dataColumns as $key => $value) {
            $colstr = PHPExcel_Cell::stringFromColumnIndex($head);
            $PHPExcelObj->getActiveSheet()->setCellValue($colstr . "1", $key);
            $PHPExcelObj->getActiveSheet()->setCellValue($colstr . "2", $value);
            $head++;
        }
        $objWriter = PHPExcel_IOFactory::createWriter($PHPExcelObj, 'Excel5');
        $objWriter->save('php://output');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="DataUploadFormat.xls"');
        header('Cache-Control: max-age=0');
        return;
    }
} else if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $errorMsg     = "";
    $successMsg   = "";
    $successCount = 0;
    if ($_FILES['file']['tmp_name']) {
        if ($_FILES['file']['type'] == "application/vnd.ms-excel") {
            $fileUploadLimit = 52428800; // files size is in bytes
            if ($_FILES['file']['size'] < $fileUploadLimit) {
                $inputFileType = "Excel5";
                $objReader     = PHPExcel_IOFactory::createReader($inputFileType);
                $objPHPExcel   = $objReader->load($_FILES['file']['tmp_name']);
                $objWorksheet  = $objPHPExcel->getActiveSheet();
                $highestColumn = PHPExcel_Cell::columnIndexFromString($objPHPExcel->getActiveSheet()->getHighestColumn());
                $highestrow    = $objPHPExcel->getActiveSheet()->getHighestRow();
                $excelarray    = [];
                $keys          = [];
                $listId        = time();
                for ($i = 1; $i <= $highestrow; $i++) {
                    $excelarray[$i] = [];
                    for ($head = 0; $head < $highestColumn; $head++) {
                        if ($i == 1) {
                            $keys[$head] = trim($objWorksheet->getCellByColumnAndRow($head, $i)->getValue());
                        } else {
                            $excelarray[$i][$keys[$head]] = trim($objWorksheet->getCellByColumnAndRow($head, $i)->getValue());
                        }
                    }
                }
                for ($i = 3; $i <= $highestrow; $i++) {
                    $excelarray[$i]['sessiontype'] = ($excelarray[$i]['sessiontype'] == 'webrtc' ? 0 : 1);
                    // print_r($excelarray[$i]);die;
                    DB::table('users')->where('username', $excelarray[$i]['username'])->update($excelarray[$i]);
                    // die;
                    $successMsg .= $excelarray[$i]["username"] . ",";
                    $successCount++;
                }
            } else {
                $errorMsg .= "File size too large, Please check file size should be less then " . ($fileUploadLimit / (1024 * 1024)) . "mb.";
            }
        } else {
            $errorMsg .= "File format not valid, Please attach Excel file (.xls) and try upload again.";
        }
        @unlink($_FILES['file']);
    } else {
        $errorMsg .= "File not found, Please attach file and try upload again.";
    }
    $success = "Data Uploaded ($successCount): " . $successMsg;
    $errFlag = 'success';
    if (isset($successMsg) && $successMsg != "") {
        $msg = $success;
    }
    if (isset($errorMsg) && $errorMsg != "") {
        $errFlag = 'failure';
        $msg     = $errorMsg;
    }
    echo json_encode(['msg' => $msg, 'status' => $errFlag]);
?>
<?php
    die;
}
?>
<div class="row">
    <div class="col-sm-12">
        <div class="panel-group" role="tablist" aria-multiselectable="true">
            <div class="panel panel-info">
                <div class="panel-heading" role="tab" id="headingOne" role="button">
                    <strong><i class="fa fa-upload"></i> Data Upload</strong>
                </div>
                <div role="tabpanel" aria-labelledby="headingOne">
                    <div class="panel-body">
                        <div class="tab_generic">
                            <!-- <p><span style="color:#f00;"><strong>Instruction</strong></span> (Works only if you have 'Write access" to the records) Please create an Excel-2003 format file with header as field-keys and rows containing record data. Extream Care is should be taken during bulk upload as previous values will be overwritten and lost.</p> -->
                            <hr style="margin-bottom: 10px;" />
                            <div class="row">
                                <div class="col-sm-3">
                                    <p><strong>Get Format</strong></p>
                                    <button type="submit" class="btn btn-success" onclick="getDataFormat();return false;"><i class="fa fa-download"></i> Get Format</button>
                                </div>
                                <div class="col-sm-9">
                                    <p><strong>Upload File</strong></p>
                                    <form method="POST" enctype="multipart/form-data" target="resultArea" action="import_excel" class="form-inline" id="upload_form">
                                        <input type="hidden" name="_token" value="{{ csrf_token() }}" />
                                        <div class="form-group">
                                            <input type="file" class="form-control" name="file" required="required" />
                                        </div>
                                        <div class="form-group">
                                            <button type="submit" class="btn btn-success"><i class="fa fa-upload"></i> Upload</button>
                                            <p>
                                                <iframe name=resultArea id="resultArea" style='width:0px;height:0px;display:none'></iframe>
                                            </p>
                                        </div>
                                    </form>
                                    <div id=ebulkuploadresult></div>
                                    <div id=loadImg></div>
                                    <div id=showsuccessmsg></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    function getDataFormat() {
        window.open('getImportExcelFormat');
        return false;
    }
</script>
<script>
    $(document).ready(function() {
        // $('#instruction').popover({ title: "<b>Note</b>", content: '(Works only if you have "<b>Write access</b>" to the records)<br>Please create an <b>Excel 2007-2013</b> format file with header as field-keys and rows containing record data.<br><span style="color: #fb6e52;">Extream Care is should be taken during bulk upload as previous values will be overwritten and lost</span>', html: true, placement: "right", trigger: 'hover' });
        // $('.reason').popover({ content: 'Click To Download Rejected Reasons', placement: "left", trigger: 'hover' });
        $('#upload_form').on('submit', function(event) {
            event.preventDefault();
            $.ajax({
                url: "import_excel",
                method: "POST",
                data: new FormData(this),
                // dataType: 'JSON',
                contentType: false,
                cache: false,
                processData: false,
                beforeSend: function() {
                    $("#loadImg").prepend("<img src='assets/images/loading.gif' class='doajax_spinner' style='position:fixed;left:50%;top:50%;margin-left:-32px;margin-top:-32px;border:0;z-index:5000' width=64px height=64px border=0>");
                },
                success: function(data) {
                    data = $.parseJSON(data);
                    if (data.status == 'failure') {
                        simpleNotification('error', 'topRight', data.msg);
                    } else {
                        simpleNotification('success', 'topRight', data.msg);
                    }
                    $("#loadImg").html("");
                    document.getElementById("upload_form").reset();
                },
            })
        });
        $('#fileSummaryTable').DataTable({
            "paging": false,
            "info": false,
            "searching": false
        });
    });
</script>