HOWTO: Give reports the ability to be exported as Excel spreadsheets

avantsys wrote on Wednesday, June 26, 2013:

Pardon me for not putting this one into a github repository, but it’s not a commit for a specific file; instead, it’s a method to get the desired results from all sorts of reports (we’ve tested it on 4.1.0 and 4.1.1 - unless you’ve modified the system beyond recognition, it should work).

Let’s break this down to a few steps:

  1. Go to the report you want to enable to be exported as an Excel spreadsheet, e.g. \interface\reports\prescriptions_report.php and open it with your preferred text editor.

  2. Add the following Javascript code to any appropriate place within the file:

#var tableToExcel = (function() {

var uri = ‘data:application/vnd.ms-excel;base64,’

, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'

, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }

, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }

return function(table, name) {

if (!table.nodeType) table = document.getElementById(table)

var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}

window.location.href = uri + base64(format(template, ctx))

}

#})()


3. Under the table with the parameters of the report, i.e. right under the line: 

, ```

add this line in order to get your “Export to excel” button:

<input type="button" onclick="tableToExcel('results2xls', 'W3C Example Table')" value=" Export as Excel">
  1. A few lines below is the table where your report results are generated. Change the “table” tag to table id=“results2xls”

  2. Save. You can apply this to any report you want and you’ll have the option to export it as an .xls file.

avantsys wrote on Wednesday, June 26, 2013:

OK, the formatting sucks and doesn’t show the code as it should. I’ll repost in a while.