Wednesday, 27 February 2019

JSON to Excel : How to export SharePoint list data into excel using JavaScript?


<script type="text/javascript" src="/SiteAssets/scripts/grid/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="/SiteAssets/scripts/grid/xlsx.core.min.js"></script>
<script type="text/javascript" src="/SiteAssets/scripts/grid/FileSaver.js"></script>
<script type="text/javascript" src="/SiteAssets/scripts/grid/jhxlsx.js"></script>


$(document).ready(function(){
loadData();
});


var exportData=[[{"text":"Resource Name"},{"text":"Resource Email"},{"text":"Status1"},{"text":"Status2"},{"text":"Supervisor Email"},{"text":"Career Level"},{"text":"Current Work Location"},{"text":"Project"},{"text":"Enterprise ID"},{"text":"Start Date"}]];

function jsonToExcel()
{

var tabularData = [{
    "sheetName": "All Resources",
    "data": exportData
}];

var options = {
    fileName: "All Resources"
};
Jhxlsx.export(tabularData, options);

}

function loadData()
{//start loadData

$().SPServices({//sart service call
    operation: "GetListItems",
    async: false,
    listName: "Resource List",
    CAMLViewFields: "<ViewFields Properties='True' />",
    CAMLQuery: "<Query><Where><Neq><FieldRef Name='ID' /><Value Type='Counter'>0</Value></Neq></Where><OrderBy><FieldRef Name='Column1' Ascending='True' /></OrderBy></Query>",
    CAMLRowLimit: 0,
    completefunc: function (xData, Status) {
      $(xData.responseXML).SPFilterNode("z:row").each(function() {
 
      exportData.push(
      [
         {"text": $(this).attr("ows_Title")},
         {"text": $(this).attr("ows_emailaddress")==undefined?"-":($(this).attr("ows_emailaddress"))},
{"text": $(this).attr("ows_status1")==undefined?"-":($(this).attr("ows_status1"))},
{"text": $(this).attr("ows_Status2")==undefined?"-":($(this).attr("ows_Status2"))},
{"text": $(this).attr("ows_SupervisorEmailID")==undefined?"-":($(this).attr("ows_SupervisorEmailID"))},
{"text": $(this).attr("ows_career_x0020_Level")==undefined?"-":($(this).attr("ows_career_x0020_Level"))},
{"text": $(this).attr("ows_Curr_Loc")==undefined?"-":($(this).attr("ows_Curr_Loc"))},
{"text": $(this).attr("ows_Project")==undefined?"-":($(this).attr("ows_Project"))},
{"text": $(this).attr("ows_Employee_x0020_ID")==undefined?"-":($(this).attr("ows_Employee_x0020_ID"))},
{"text": $(this).attr("ows_Start_x0020_Date")==undefined?"-":($(this).attr("ows_Start_x0020_Date"))}
]
       );
     
      });//end loop
    }

  });//end service call

}//end loadData


Reference: https://www.jqueryscript.net/other/JavaScript-JSON-Data-Excel-XLSX.html

No comments:

Post a Comment