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);
}

No comments:

Post a Comment