Export To Word Utility In SharePoint 2013/Online Using JavaScript

Many a time we need the SharePoint list data in the word file rather than in the Excel (provided by SharePoint). In that case user can use this Utility. This Utility can export the Single selected list Item as well as multiple selected List item. 
To use this utility just copy the code and add it in the content editor in the page of your list.

In SharePoint there is Export to Excel functionality but it gives all the items in the List with all rows and columns...It doesn't give the feature to:
  • Export Selected rows
  • Limited Columns
To use this utility just copy the code and add it in the content editor in the page of your list. Edit a Page, Add a webpart, media Content webpart, Add Content Editor, Add the code after uncommenting one line(Highlighted in green),
  1. <script src="//code.jquery.com/jquery-1.10.1.min.js"></script>  
  2. <script>  
  3.     var tempTableId;  
  4.     var tempTitle;  
  5.     var row;  
  6.     var rowData;  
  7.     var context;  
  8.     var selectedItems;  
  9.     var selectedList;  
  10.     var oList;  
  11.     var oFieldCollection;  
  12.     var collListItem;  
  13.     var mainExportContainer;  
  14.     var table;  
  15.     var fieldEnumerator;  
  16.     var oField;  
  17.     var fieldsArray = ['ID''Title'];  
  18.     //var fieldsArray = ['ID','Title','Male','Female','new_x0020_test']; //Insert the internal name of the column of your list.Note : ID column and Title is mandatory.Please uncomment the line.  
  19.     var viewname;  
  20.     var listColumns;  
  21.   
  22.     function exportSelectedItemsToWord() {  
  23.         this.context = SP.ClientContext.get_current();  
  24.         this.selectedItems = SP.ListOperation.Selection.getSelectedItems(context);  
  25.         this.selectedList = SP.ListOperation.Selection.getSelectedList();  
  26.         this.oList = SP.ClientContext.get_current().get_web().get_lists().getById(selectedList);  
  27.         // to get the selected item and the selected List.  
  28.         var camlQuery = new SP.CamlQuery();  
  29.         var stringCamlQuery = "<View><ViewFields>"  
  30.         stringCamlQuery = "<View>" + "<Query>" + "<Where>" + "<In>" + "<FieldRef Name='ID' />" + "<Values>";  
  31.         for (var i = 0; i < selectedItems.length; i++) {  
  32.             stringCamlQuery += "<Value Type='Integer'>" + selectedItems[i].id + "</Value>";  
  33.         }  
  34.         stringCamlQuery += "</Values>" + "</In>" + "</Where>" + "</Query>" + "</View>";  
  35.         var strColumnsInclude = 'Include(';  
  36.         for (var i = 0; i < fieldsArray.length - 1; i++) {  
  37.             strColumnsInclude += fieldsArray[i] + ', ';  
  38.         }  
  39.         strColumnsInclude += fieldsArray[i] + ')';  
  40.         camlQuery.set_viewXml(stringCamlQuery);  
  41.         this.collListItem = oList.getItems(camlQuery);  
  42.         context.load(this.collListItem, strColumnsInclude);  
  43.         context.executeQueryAsync(Function.createDelegate(thisthis.onQueryexportSucceeded), Function.createDelegate(thisthis.onQueryexportFailed));  
  44.     }  
  45.     //Creating a html table of the retrieved selected item.  
  46.     function onQueryexportSucceeded() {  
  47.         var fieldName, fieldValue;  
  48.         $('#mainExportContainer').html('');  
  49.         mainExportContainer = $('<div></div>').attr('id''mainExportContainer').css('display''none');  
  50.         $("<h1 align='center'>List Item(s)</h2>").appendTo("#mainExportContainer"); // Heading of the Word document Page.  
  51.         itemEnumerator = this.collListItem.getEnumerator();  
  52.         var $table;  
  53.         while (itemEnumerator.moveNext()) {  
  54.             this.oListItem = itemEnumerator.get_current();  
  55.             tempTableId = 'listItem_' + this.oListItem.get_item('ID');  
  56.             tempTitle = this.oListItem.get_item('Title');  
  57.             $('<h2 align="center">' + tempTitle + '</h2>').appendTo('#mainExportContainer');  
  58.             $table = $('<table></table>');  
  59.             $table.attr('id', tempTableId);  
  60.             $("<thead><tr><td><b>Column Name</b></td><td><b>Column Value</b></td><tr></thead>").appendTo($table);  
  61.             //Creating Column Name and Column Value as a rows.  
  62.             var strValues;  
  63.             var j;  
  64.             for (var i = 0; i < fieldsArray.length; i++) {  
  65.                 fieldName = fieldsArray[i];  
  66.                 var tempfieldName = fieldName.replace(/\_[^_]*\_/g, ' ');  
  67.                 row = $('<tr></tr>');  
  68.                 rowData = $('<td></td>').addClass('fieldName').text(tempfieldName);  
  69.                 row.append(rowData);  
  70.                 fieldValue = this.oListItem.get_item(fieldName);  
  71.                 if (fieldValue != null) {  
  72.                     if (fieldValue.constructor.toString() == SP.FieldUserValue.toString()) {  
  73.                         rowData = $('<td></td>').addClass('fieldValue').text(strip(fieldValue.get_lookupValue()));  
  74.                     } else if (fieldValue.constructor.toString() == SP.FieldLookupValue.toString()) {  
  75.                         rowData = $('<td></td>').addClass('fieldValue').text(strip(fieldValue.get_lookupValue()));  
  76.                     } else if (fieldValue.constructor.toString() == "function Array() { [native code] }") {  
  77.                         for (j = 0; j < fieldValue.length - 1; j++) {  
  78.                             strValues += fieldValue[j] + ", ";  
  79.                         }  
  80.                         strValues += fieldValue[j];  
  81.                         rowData = $('<td></td>').addClass('fieldValue').text(strip(strValues));  
  82.                     } else {  
  83.                         rowData = $('<td></td>').addClass('fieldValue').text(strip(fieldValue));  
  84.                     }  
  85.                 } else {  
  86.                     rowData = $('<td></td>').addClass('fieldValue').text('');  
  87.                 }  
  88.                 row.append(rowData);  
  89.                 $table.append(row);  
  90.             }  
  91.             $table.appendTo($('#mainExportContainer'));  
  92.             $('<br style="page-break-before: always">').appendTo($('#mainExportContainer'));  
  93.         }  
  94.         $("#mainExportContainer table tr td:first-child").css('background-color''grey');  
  95.         $("#mainExportContainer img").remove();  
  96.         var htmlData = '<html xmlns:office="urn:schemas-microsoft-com:office:office" xmlns:word="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"><head><xml><word:WordDocument><word:View>Print</word:View><word:Zoom>90</word:Zoom><word:DoNotOptimizeForBrowser/></word:WordDocument></head><body>' + document.getElementById('mainExportContainer').innerHTML + "</body></html>";  
  97.         exportElementToWord(htmlData);  
  98.         //Passing the Html to microsoft uri to export it as Word file  
  99.     }  
  100.   
  101.     function onQueryexportFailed(sender, args) {  
  102.         alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());  
  103.     }  
  104.   
  105.     function exportElementToWord(html) {  
  106.         if (navigator.appName === "Microsoft Internet Explorer") {  
  107.             var iframe = document.getElementById('htmlDownloadFrame');  
  108.             iframe = iframe.contentWindow || iframe.contentDocument;  
  109.             iframe.document.open("text/html""replace");  
  110.             iframe.document.write(html);  
  111.             iframe.document.close();  
  112.             iframe.focus();  
  113.             iframe.document.execCommand('SaveAs'true'Word.doc');  
  114.         } else {  
  115.             if (console && console.log) {  
  116.                 console.log('Trying to call getCsvFileForIE with non IE browser.');  
  117.             }  
  118.         }  
  119.     }  
  120.   
  121.     function strip(html) {  
  122.         var tmp = document.createElement("DIV");  
  123.         tmp.innerHTML = html;  
  124.         return tmp.textContent || tmp.innerText || "";  
  125.     }  
  126. </script>  
  127. <div id="mainExportContainer" style="display: none;"> </div> <iframe id="htmlDownloadFrame" style="display: none;"></iframe>  
  128. <td> <input type="button" id="btnSubmit" value="Export to word" onclick=" exportSelectedItemsToWord()" style="  
  129. margin-left: 163px ;margin-bottom:14px; color: #fff;  
  130. background-color: #6496c8;  
  131. border: none;  
  132. border-radius: 15px;  
  133. box-shadow: 0 10px #27496d;" /> </td>  

Read more articles on SharePoint:

Up Next
    Ebook Download
    View all
    Learn
    View all