Thursday, 25 June 2020

Sorting String Date Array in ascending and Descending Order

https://jsfiddle.net/w8Lozex7/3/

http://jsfiddle.net/ot24zrkt/117/

var dateArr = new Array();
dateArr[0] = "11-12-2012";
dateArr[1] = "9-12-2014";
dateArr[2] = "11-12-2012";
dateArr[3] = "9-12-2011";


var arr = [];
for(var i =0; i<dateArr.length; i++)
{
    date1 = dateArr[i].split("-");
    if(date1[0]<10){date1[0]='0'+date1[0]}
    if(date1[1]<10){date1[1]='0'+date1[1]}
    arr.push(new Date(date1[2], date1[1] - 1, date1[0]));
}

arr.sort(function(a,b){return a-b});  //asc
console.log(formatDateArr(arr));

arr.sort(function(a,b){return b-a});  //desc
console.log(formatDateArr(arr));

function formatDateArr(arr)
{
    formatedArr = [];
    for(var i=0; i<arr.length; i++)
    {
        var curr_date = arr[i].getDate();
        var curr_month = arr[i].getMonth() + 1; //Months are zero based
        var curr_year = arr[i].getFullYear();
        formatedArr.push(curr_date + "-" + curr_month + "-" + curr_year);
    }
    return formatedArr;
}

Tuesday, 23 June 2020

Read Excel as csv from SharePoint library using JavaScript

  1. function readTextFile(file) {  
  2.     var rawFile = new XMLHttpRequest();  
  3.     rawFile.open("GET", file, false);  
  4.     rawFile.onreadystatechange = function () {  
  5.         if (rawFile.readyState === 4) {  
  6.             if (rawFile.status === 200 || rawFile.status == 0) {  
  7.                 var allText = rawFile.responseText;  
  8.                 alert(allText);  
  9.             }  
  10.         }  
  11.     }  
  12.     rawFile.send(null);  
  13. }  


I changed my file format and changed to CSV from excel. What I did is, I have used following code:


https://social.technet.microsoft.com/Forums/en-US/06d7686e-896e-4892-a9f0-ebae2d9ff799/how-to-readwriteupdate-a-csv-file-present-in-an-document-library-using-javascript?forum=sharepointgeneral

https://www.js-tutorials.com/jquery-tutorials/reading-csv-file-using-jquery/
$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "data.txt",
        dataType: "text",
        success: function(data) {processData(data);}
     });
});

function processData(allText) {
    var record_num = 5;  // or however many elements there are in each row
    var allTextLines = allText.split(/\r\n|\n/);
    var entries = allTextLines[0].split(',');
    var lines = [];

    var headings = entries.splice(0,record_num);
    while (entries.length>0) {
        var tarr = [];
        for (var j=0; j<record_num; j++) {
            tarr.push(headings[j]+":"+entries.shift());
        }
        lines.push(tarr);
    }
    // alert(lines);
}

function processData(allText) {
    var allTextLines = allText.split(/\r\n|\n/);
    var headers = allTextLines[0].split(',');
    var lines = [];

    for (var i=1; i<allTextLines.length; i++) {
        var data = allTextLines[i].split(',');
        if (data.length == headers.length) {

            var tarr = [];
            for (var j=0; j<headers.length; j++) {
                tarr.push(headers[j]+":"+data[j]);
            }
            lines.push(tarr);
        }
    }
    // alert(lines);
}

Monday, 22 June 2020

Reading an excel file using HTML 5 and jQuery and save in SharePoint list



Friday, December 8, 2017

Reading an excel file using HTML 5 and jQuery and save in SharePoint list

Reading an excel file using HTML 5 and jQuery and save in SharePoint list
Reference
https://github.com/SheetJS/js-xlsx
https://github.com/SheetJS/js-xls
Step 1: First create a SharePoint list and give list name as "EmployeeDetails".
Step 2: Write a below code in HTML file and name it as "ExcelToSPListItems.html". Upload this file into SharePoint assets library. This HTML code file will refer in Content Editor WebPart so please copy file url after upload into assets library.
The below code first will check "Employee ID" in list, if "Employee ID" exist then that item will update current item else new item will create in SharePoint list.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>EmployeeDetails</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.7.7/xlsx.core.min.js" type="text/javascript"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.core.min.js" type="text/javascript"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
    <style>
        table {
            margin-top20px;
            border-collapsecollapse;
            displaynone;
        }

            table th, table td {
                border1px solid #000;
                padding5px 10px;
            }
    </style>
    <script type="text/javascript">
        function ExportToTable() {
            $('#loading').show();
            var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xlsx|.xls)$/;
            if (regex.test($("#excelfile").val().toLowerCase())) {
                var xlsxflag = false;
                if ($("#excelfile").val().toLowerCase().indexOf(".xlsx") > 0) {
                    xlsxflag = true;
                }
                if (typeof (FileReader) != "undefined") {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var data = e.target.result;
                        if (xlsxflag) {
                            var workbook = XLSX.read(data, { type: 'binary' });
                        }
                        else {
                            var workbook = XLS.read(data, { type: 'binary' });
                        }
                        var sheet_name_list = workbook.SheetNames;
                        var cnt = 0;
                        sheet_name_list.forEach(function (y) {
                            if (xlsxflag) {
                                var exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
                            }
                            else {
                                var exceljson = XLS.utils.sheet_to_row_object_array(workbook.Sheets[y]);
                            }
                            if (exceljson.length > 0 && cnt == 0) {
                                BindTable(exceljson'#exceltable');
                                exceljson.forEach(function (excelRow) {
                                    if (excelRow != null && Object.keys(excelRow).length > 0 && excelRow["Employee ID"] != null && excelRow["Employee ID"].toString() != "") {
                                        getEmployeeDetailsByEmployeeID(excelRow["Employee ID"].toString().trim(), excelRow);
                                    }
                                });
                                cnt++;
                            }
                        });
                        $('#loading').hide();
                        $('#exceltable').show();
                    }
                    if (xlsxflag) {
                        reader.readAsArrayBuffer($("#excelfile")[0].files[0]);
                    }
                    else {
                        reader.readAsBinaryString($("#excelfile")[0].files[0]);
                    }
                }
                else {
                    $('#loading').hide();
                    alert("Sorry! Your browser does not support HTML5!");
                }
            }
            else {
                $('#loading').hide();
                alert("Please upload a valid Excel file!");
            }
        }
        function BindTable(jsondatatableid) {
            var columns = BindTableHeader(jsondatatableid);
            for (var i = 0i < jsondata.lengthi++) {
                var row$ = $('<tr/>');
                for (var colIndex = 0colIndex < columns.lengthcolIndex++) {
                    var cellValue = jsondata[i][columns[colIndex]];
                    if (cellValue == null)
                        cellValue = "";
                    row$.append($('<td/>').html(cellValue));
                }
                $(tableid).append(row$);
            }
        }
        function BindTableHeader(jsondatatableid) {
            var columnSet = [];
            var headerTr$ = $('<tr/>');
            for (var i = 0i < jsondata.lengthi++) {
                var rowHash = jsondata[i];
                for (var key in rowHash) {
                    if (rowHash.hasOwnProperty(key)) {
                        if ($.inArray(keycolumnSet) == -1) {
                            columnSet.push(key);
                            headerTr$.append($('<th/>').html(key));
                        }
                    }
                }
            }
            $(tableid).append(headerTr$);
            return columnSet;
        }
        function getEmployeeDetailsByEmployeeID(EmployeeIDValueexcelRow) {
            var objHeaders = {
                type: "GET",
                headers: {
                    "accept": "application/json;odata=verbose"
                },
                async: false,
                mode: 'cors',
                cache: 'no-cache',
                credentials: 'include'
            }
            fetch(_spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee Details')/items?$filter=Employee_x0020_ID eq '" + EmployeeIDValue + "'&$select=ID,Title,Employee_x0020_ID,Address&$orderby=ID"objHeaders)
                .then(function (response) {
                    return response.json()
                })
            .then(function (json) {
                var results = json.d.results;
                if (results.length > 0) {
                    for (i in results) {
                        updateEmployeeDetailsListItem(results[i].IDexcelRow);
                    }
                }
                else {
                    createEmployeeDetailsListItem(excelRow);
                }
            })
            .catch(function (ex) {
                console.log("error");
            });
        }
        function updateEmployeeDetailsListItem(itemIDexcelRow) {
            $.ajax
            ({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee Details')/items(" + itemID + ")",
                type: "POST",
                data: JSON.stringify
                ({
                    __metadata:
                    {
                        type: "SP.Data.EmployeeDetailsListItem"
                    },
                    Employee_x0020_ID: excelRow["Employee ID"],
                    Address: excelRow["Address"]
                }),
                headers:
                {
                    "Accept": "application/json;odata=verbose",
                    "Content-Type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "IF-MATCH": "*",
                    "X-HTTP-Method": "MERGE"
                },
                async: false,
                success: function (datastatusxhr) {
                    console.log("success");
                },
                error: function (xhrstatuserror) {
                    console.log("errro");
                }
            });
        }
        function createEmployeeDetailsListItem(excelRow) {
            $.ajax
                ({
                    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('Employee Details')/items",
                    type: "POST",
                    data: JSON.stringify
                    ({
                        __metadata:
                        {
                            type: "SP.Data.EmployeeDetailsListItem"
                        },
                        Title: excelRow["Employee Name"],
                        Employee_x0020_ID: excelRow["Employee ID"],
                        Address: excelRow["Address"]
                    }),
                    headers:
                    {
                        "Accept": "application/json;odata=verbose",
                        "Content-Type": "application/json;odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                        "X-HTTP-Method": "POST"
                    },
                    success: function (datastatusxhr) {
                        console.log("success");
                    },
                    error: function (xhrstatuserror) {
                        console.log("error");
                    }
                });
        }
    </script>
</head>
<body>
    <input type="file" id="excelfile" />
    <input type="button" id="viewfile" value="Export To Table and SPList" onclick="ExportToTable()" /> <br />
    Reference <br />
    <a href="https://github.com/SheetJS/js-xlsx">https://github.com/SheetJS/js-xlsx</a> <br />
    <a href="https://github.com/SheetJS/js-xls">https://github.com/SheetJS/js-xlsx</a> <br />
    <p id="loading" style="display:none;">Loading please wait. <i class="fa fa-spinner fa-spin" style="font-size:24px;"></i> </p> <br />
    <table id="exceltable"></table> <br />
</body>
</html>
Now upload above "ExcelToSPListItems.html" file into site assets library.
 Step 3: Create an webpart page and save in Page library. Now edit this page and add Content Editor Webpart.
Step 4: To test the application first create an excel file with below values and save as "EmployeeDetails.xlsx".
Step 5: Now test the application. upload excel file and check in SharePoint list. Excel list must created or updated.