Introduction

Normally developers download Excel of any other file format from the server-side. It may be the correct way to do the exporting if and only if the data is quite small. As you all know, when you develop a product or website, you may need to convince many people including in that project. You must convince your client because he/she is paying for it. :) Your client will always look at whether your product is worth the money he will spend.
Background
For the past few months, I am working on client-side exporting, compression, decompression and so on.
Before going through the client-side mechanisms, you must be aware of what all the problems are in server-side exporting.

The Process

The process that I will do is so simple.
You may need to look at my previous article that explains the Excel exporting mechanism on the client-side.
  1. Export From HTML Table Using jQuery.
  2. Export Hierarchical (Multi-Level) HTML Table With Styles Using jQuery.
Here I am listing what exactly I am going to do with my data.
1. Please find the SampleExcelFileData file. Consider that I have data as in that document. You can see some content but there is not much. I am giving you a demo with that content. I have taken this data from the JQX Grid. For the past few months I have been working in JQX JQwidgets, the implementation I have done is for using it in my JQX grid. If you are new to JQX Grid you can check the following links. 2. Once the data is ready we can go with the compression part. We have the XML string as our data. We are going with the client-side compression mechanism.
For the compression I have used LZW compression, please find more here.
The following is the code for the compression:
  1. var LZW = {
  2. compress: function (uncompressed) {
  3. "use strict";
  4. // Build the dictionary.
  5. var i,
  6. dictionary = {},
  7. c,
  8. wc,
  9. w = "",
  10. result = [],
  11. dictSize = 256;
  12. for (i = 0; i < 256; i += 1) {
  13. dictionary[String.fromCharCode(i)] = i;
  14. }
  15. for (i = 0; i < uncompressed.length; i += 1) {
  16. c = uncompressed.charAt(i);
  17. wwc = w + c;
  18. //Do not use dictionary[wc] because javascript arrays
  19. //will return values for array['pop'], array['push'] etc
  20. // if (dictionary[wc]) {
  21. if (dictionary.hasOwnProperty(wc)) {
  22. w = wc;
  23. } else {
  24. result.push(dictionary[w]);
  25. // Add wc to the dictionary.
  26. dictionary[wc] = dictSize++;
  27. w = String(c);
  28. }
  29. }
  30. if (w !== "") {
  31. result.push(dictionary[w]);
  32. }
  33. return result;
  34. }
  35. }
The preceding code does the compression, now we need to check the implementation. Am I right?
  1. $("#excelExport").click(function () {
  2. var exportInfo = LZW.compress($("#jqxgrid").jqxGrid('exportdata', 'xls'));
  3. });
    In the preceding code, you can see that I am compressing the data that I have taken from the JQX Grid.
    You can get the grid data as follows.
    1. $("#jqxgrid").jqxGrid('exportdata', 'xls');
    To learn more about exporting in JQX Grid, please see here: Advanced JQX Grid With All Functionality.
    You can always decompress the data as follows.
    1. decompressedVariable = LZW.decompress(exportInfo);
    The following is the code for the decompression:
    1. decompress: function (compressed) {
    2. "use strict";
    3. // Build the dictionary.
    4. var i,
    5. dictionary = [],
    6. w,
    7. result,
    8. k,
    9. entry = "",
    10. dictSize = 256;
    11. for (i = 0; i < 256; i += 1) {
    12. dictionary[i] = String.fromCharCode(i);
    13. }
    14. w = String.fromCharCode(compressed[0]);
    15. result = w;
    16. for (i = 1; i < compressed.length; i += 1) {
    17. k = compressed[i];
    18. if (dictionary[k]) {
    19. entry = dictionary[k];
    20. } else {
    21. if (k === dictSize) {
    22. entry = w + w.charAt(0);
    23. } else {
    24. return null;
    25. }
    26. }
    27. result += entry;
    28. // Add w+entry[0] to the dictionary.
    29. dictionary[dictSize++] = w + entry.charAt(0);
    30. w = entry;
    31. }
    32. return result;
    33. }
      Output Compression And Decompression:
      cs code
      code
      In the preceding image, you can see the length of the content before compression and after compression.
      Before compression, the length is 41447. And after compression, the length is 5452.
      Now we know how to compress and decompress the contents :).
      Cool. We have done it.
      What else is pending? Yeah, you are right, we need to export that content.

      Exporting Using BLOB

      Excel exporting is an important feature in every application. Yeah, we do have an Excel exporting mechanism. :)
      For the Excel exporting we are using a new technology called BLOB in HTML5.
      To work on it, you need to attach the script:
      1. <script src="FileSaver.min.js"></script>
      This script does the saving of the Excel file. So it is important that we include it though.
      So once you have included that file we can move on to the next level.
      The Implementation
      The following code explains the implementation.
      1. //This will download the excel file without compression (before compression of data)
      2. saveMyFile($('#SubmitForm'), "My Excel File" + ".xls", $("#jqxgrid").jqxGrid('exportdata', 'xls'), 'text/xls;charset=utf-8');
      3. //this will download the file with compression (after compression of the data)
      4. saveMyFile($('#SubmitForm'), "My Excel File" + ".xls", exportInfo, 'text/xls;charset=utf-8');
      You can see that the parameters of the function saveMyFile,
      1. Reference form.
      2. File name.
      3. The string to be exported. In our case, it is our XML string.
      4. The mime type, for example: 'text/xls;charset=utf-8'.

      The export function

      1. function saveMyFile(ref, fname, text, mime) {
      2. var blob = new Blob([text], { type: mime });
      3. saveAs(blob, fname);
      4. return false;
      5. }
      Once you pass the parameters, this function will do the remaining of what needs to be done. Sounds great, right? :)
      Your Excel file will be exported in a fraction of a second.
      Great work by the Blob function. :)
      See the file size difference
      Now I hope you have two downloaded files:
      1. Without compression
      2. With compression
      Let us see the size difference now.
      excel file
      Here, My Excel File.xls is without compression and My Excel File(1).xls is with compression. I hope you see the difference. :)
      Now it is time for the complete HTML.
      1. <!DOCTYPE html>
      2. <html lang="en">
      3. <head>
      4. <title id='Description'>This example illustrates how to customize the filtering conditions available in the columns popup menu.
      5. </title>
      6. <script src="jquery-1.9.1.js"></script>
      7. <script type="text/javascript" src="JQXItems/jqwidgets/jqxcore.js"></script>
      8. <script type="text/javascript" src="JQXItems/jqwidgets/jqxdata.js"></script>
      9. <script type="text/javascript" src="JQXItems/jqwidgets/jqxbuttons.js"></script>
      10. <script type="text/javascript" src="JQXItems/jqwidgets/jqxscrollbar.js"></script>
      11. <script type="text/javascript" src="JQXItems/jqwidgets/jqxlistbox.js"></script>
      12. <script type="text/javascript" src="JQXItems/jqwidgets/jqxdropdownlist.js"></script>
      13. <script type="text/javascript" src="JQXItems/jqwidgets/jqxgrid.js"></script>
      14. <script type="text/javascript" src="JQXItems/jqwidgets/jqxgrid.filter.js"></script>
      15. <script type="text/javascript" src="JQXItems/jqwidgets/jqxgrid.sort.js"></script>
      16. <script type="text/javascript" src="JQXItems/jqwidgets/jqxgrid.selection.js"></script>
      17. <script type="text/javascript" src="JQXItems/jqwidgets/jqxgrid.pager.js"></script>
      18. <script type="text/javascript" src="JQXItems/jqwidgets/jqxgrid.columnsresize.js"></script>
      19. <script type="text/javascript" src="JQXItems/jqwidgets/jqxgrid.columnsreorder.js"></script>
      20. <script type="text/javascript" src="JQXItems/jqwidgets/jqxgrid.export.js"></script>
      21. <script type="text/javascript" src="JQXItems/jqwidgets/jqxdata.export.js"></script>
      22. <script type="text/javascript" src="JQXItems/jqwidgets/jqxdatatable.js"></script>
      23. <script src="JQXItems/jqwidgets/jqxcheckbox.js"></script>
      24. <script src="JQXItems/jqwidgets/jqxmenu.js"></script>
      25. <link href="JQXItems/jqwidgets/styles/jqx.base.css" rel="stylesheet" />
      26. <script src="generatedata.js"></script>
      27. <script src="FileSaver.min.js"></script>
      28. <script type="text/javascript">
      29. $(document).ready(function () {
      30. var LZW = {
      31. compress: function (uncompressed) {
      32. "use strict";
      33. // Build the dictionary.
      34. var i,
      35. dictionary = {},
      36. c,
      37. wc,
      38. w = "",
      39. result = [],
      40. dictSize = 256;
      41. for (i = 0; i < 256; i += 1) {
      42. dictionary[String.fromCharCode(i)] = i;
      43. }
      44. for (i = 0; i < uncompressed.length; i += 1) {
      45. c = uncompressed.charAt(i);
      46. wc = w + c;
      47. //Do not use dictionary[wc] because javascript arrays
      48. //will return values for array['pop'], array['push'] etc
      49. // if (dictionary[wc]) {
      50. if (dictionary.hasOwnProperty(wc)) {
      51. w = wc;
      52. } else {
      53. result.push(dictionary[w]);
      54. // Add wc to the dictionary.
      55. dictionary[wc] = dictSize++;
      56. w = String(c);
      57. }
      58. }
      59. if (w !== "") {
      60. result.push(dictionary[w]);
      61. }
      62. return result;
      63. },
      64. decompress: function (compressed) {
      65. "use strict";
      66. // Build the dictionary.
      67. var i,
      68. dictionary = [],
      69. w,
      70. result,
      71. k,
      72. entry = "",
      73. dictSize = 256;
      74. for (i = 0; i < 256; i += 1) {
      75. dictionary[i] = String.fromCharCode(i);
      76. }
      77. w = String.fromCharCode(compressed[0]);
      78. result = w;
      79. for (i = 1; i < compressed.length; i += 1) {
      80. k = compressed[i];
      81. if (dictionary[k]) {
      82. entry = dictionary[k];
      83. } else {
      84. if (k === dictSize) {
      85. entry = w + w.charAt(0);
      86. } else {
      87. return null;
      88. }
      89. }
      90. result += entry;
      91. // Add w+entry[0] to the dictionary.
      92. dictionary[dictSize++] = w + entry.charAt(0);
      93. w = entry;
      94. }
      95. return result;
      96. }
      97. }
      98. var url = "products.xml";
      99. // prepare the data
      100. var source =
      101. {
      102. datatype: "xml",
      103. datafields: [
      104. { name: 'ProductName', type: 'string' },
      105. { name: 'QuantityPerUnit', type: 'int' },
      106. { name: 'UnitPrice', type: 'float' },
      107. { name: 'UnitsInStock', type: 'float' },
      108. { name: 'Discontinued', type: 'bool' }
      109. ],
      110. root: "Products",
      111. record: "Product",
      112. id: 'ProductID',
      113. url: url
      114. };
      115. var cellclass = function (row, columnfield, value) {
      116. if (value < 20) {
      117. return 'red';
      118. }
      119. else if (value >= 20 && value < 50) {
      120. return 'yellow';
      121. }
      122. else return 'green';
      123. }
      124. var dataAdapter = new $.jqx.dataAdapter(source, {
      125. downloadComplete: function (data, status, xhr) { },
      126. loadComplete: function (data) { },
      127. loadError: function (xhr, status, error) { }
      128. });
      129. // initialize jqxGrid
      130. $("#jqxgrid").jqxGrid(
      131. {
      132. width: 850,
      133. source: dataAdapter,
      134. pageable: true,
      135. autoheight: true,
      136. sortable: true,
      137. altrows: true,
      138. enabletooltips: true,
      139. columns: [
      140. { text: 'Product Name', datafield: 'ProductName', width: 250 },
      141. { text: 'Quantity per Unit', datafield: 'QuantityPerUnit', cellsalign: 'right', align: 'right', width: 120 },
      142. { text: 'Unit Price', datafield: 'UnitPrice', align: 'right', cellsalign: 'right', cellsformat: 'c2', width: 100 },
      143. { text: 'Units In Stock', datafield: 'UnitsInStock', cellsalign: 'right', cellclassname: cellclass, width: 100 },
      144. { text: 'Discontinued', columntype: 'checkbox', datafield: 'Discontinued' },
      145. ]
      146. });
      147. $("#excelExport").click(function () {
      148. debugger;
      149. var decompressedVariable;
      150. console.log($("#jqxgrid").jqxGrid('exportdata', 'xls'));
      151. var exportInfo = LZW.compress($("#jqxgrid").jqxGrid('exportdata', 'xls'));
      152. //This will download the excel file without compression (before compression of data)
      153. saveMyFile($('#SubmitForm'), "My Excel File" + ".xls", $("#jqxgrid").jqxGrid('exportdata', 'xls'), 'text/xls;charset=utf-8');
      154. //this will download the file with compression (after compression of the data)
      155. saveMyFile($('#SubmitForm'), "My Excel File" + ".xls", exportInfo, 'text/xls;charset=utf-8');
      156. decompressedVariable = LZW.decompress(exportInfo);
      157. });
      158. function saveMyFile(ref, fname, text, mime) {
      159. var blob = new Blob([text], { type: mime });
      160. saveAs(blob, fname);
      161. return false;
      162. }
      163. });
      164. </script>
      165. </head>
      166. <body class='default'>
      167. <input type="button" value="Export to Excel" id='excelExport' />
      168. <style>
      169. .green {
      170. color: black\9;
      171. background-color: #b6ff00\9;
      172. }
      173. .yellow {
      174. color: black\9;
      175. background-color: yellow\9;
      176. }
      177. .red {
      178. color: black\9;
      179. background-color: #e83636\9;
      180. }
      181. .green:not(.jqx-grid-cell-hover):not(.jqx-grid-cell-selected), .jqx-widget .green:not(.jqx-grid-cell-hover):not(.jqx-grid-cell-selected) {
      182. color: black;
      183. background-color: #b6ff00;
      184. }
      185. .yellow:not(.jqx-grid-cell-hover):not(.jqx-grid-cell-selected), .jqx-widget .yellow:not(.jqx-grid-cell-hover):not(.jqx-grid-cell-selected) {
      186. color: black;
      187. background-color: yellow;
      188. }
      189. .red:not(.jqx-grid-cell-hover):not(.jqx-grid-cell-selected), .jqx-widget .red:not(.jqx-grid-cell-hover):not(.jqx-grid-cell-selected) {
      190. color: black;
      191. background-color: #e83636;
      192. }
      193. </style>
      194. <div id='jqxWidget' style="font-size: 13px; font-family: Verdana; float: left;">
      195. <div id="jqxgrid">
      196. </div>
      197. </div>
      198. </body>
      199. </html>
        Note: I have implemented the grid with a color render implementation. You can omit it and implement a simple grid if you work on the JQX Grid. Please note that you can give any string for the compression and decompression. For my convenience, I selected the JQX Grid data.

        Conclusion

        Please download the attachment and try it. Please do not forget to give your valuable suggestions.
        Point of interest
        Export, Client-side Export, Compression on the client-side, Decompression on the client-side, Export using BLOB, Export in jQuery.
        That is all for the day, will see you in another article.
        Kindest Regards,
        Sibeesh