tostasqb tostasqb - 1 month ago 18x
jQuery Question

Export json to excel

I have a search page which retrieves data from one database table and I display it like a pivot table using a bunch of jquery plugins and some written code.

What I want to do: export both sources to excel, the original data and the treated to be pivot like.

Some code:

$('#btn-apply').click(function() {
params = buildParams(); //-> json object structure

url: '<%= pivot_apply_path%>',
type: "GET",
dataType: "html",
data: params,
success: function(result) {
json.source = $.parseJSON(result); //-> original json response and data from acctiverecord
json.pivot = pivot(, params.rows, params.columns, {}); //-> treated data to another json
html = tableGeneration(json.pivot); //-> generate a table from the treated json and show it

This all works great, but now the challenge:

  1. Click a button, send the source json, and retrieve and excel with this data

  2. Click a button, send the pivot json, and retrieve and excel with this data

What I did:

  1. Pass both the source json to the controller and received like this

def export_table

@records = params

respond_to do |format|


I already have a view export_source.xls.erb which is the technique I used before to export a xls, all the formatting works fine. The problem is the response to the json call...

$('.export-table').click(function(e) {
url: '<%= pivot_export_table_path%>',
type: "POST",
dataType: "xls",
data: { data: json.pivot },
success: function(result) {
error: function (request, status, error) {
showMessage('error', error); //<- ENDS UP HERE

As this is not a postback link so it doesn't postback my xls, worse, it doesn't even enter my ajax success, it goes directly to error with the description
No conversion from text to xls



This discussion with slicedpan left me thinking on one solution:

  1. Make a form on my view with an input text hidden
  2. Submit my form in a simple Post (no ajax)
  3. On the click of the button (before the post) put the json stringified on the input
  4. Read it on the controller with ActiveSupport::JSON.decode(value) side and render the format.xls as always

Just tested it, and works ok, pitty this solution is not so pretty...I will still leave this open for someone to come up with a nicer one.

Right on!