Tuesday, March 7, 2017

JavaScript - Simple Export to excel

To export excel in JavaScript without any server side techiques, we can use following steps

Used blob file saver for download https://github.com/eligrey/FileSaver.js

Step 1: Create Html Content with required styles as below

var tableHtml = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">';
        tableHtml += '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets>';
        tableHtml += '<x:ExcelWorksheet><x:Name>PlanFundLineup</x:Name>';
        tableHtml += '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>';
        tableHtml += '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';
  tableHtml += "<div><table  border='1'>" +
        tableHtml += "<thead>" +
        tableHtml += "<tr><th>" +
        tableHtml += "Header Text" +
        tableHtml += "</th></tr>" +
 tableHtml += "</thead>" +
               "<tbody>" +
        tableHtml += "<tr><td>" +
        tableHtml += "Content Text" +
        tableHtml += "</td></tr>" +
               "</tbody>" +
              "</table></div>";
        tableHtml += '</body></html>';

Step 2: Download this html content using blob

var blob = new Blob([tableHtml], { type: "application/vnd.ms-excel;charset=utf-8" })
window.saveAs(blob, "excelname.xls");


No comments:

Post a Comment