-1

Is it possible to generate a file on client side using Javascript/AJAX and the server side response (a string, for example) and then open this file download window? A simple .txt, for example.

And if it is possible, is there any solution which generates .xlsx files?

victorf
  • 978
  • 2
  • 17
  • 35

1 Answers1

2

This will create a CSV that you can open in excel based on an array of objects (window.EXPORTDATA):

        var csvContent = [];

        for(var i=0; i<window.EXPORTDATA.length; i++){
          var rowContent = [];
          var row = window.EXPORTDATA[i];
          if(csvContent.length === 0){
            for(var p in row)
              if(row.hasOwnProperty(p))
                rowContent.push('"'+ (""+p).replace('"','').replace(',','') +'"');
            csvContent.push("data:text/csv;charset=utf-8,"+rowContent.join(","));
            rowContent = [];
          }
          for(var p in row){
            if(row.hasOwnProperty(p))
              rowContent.push('"'+ (""+row[p]).replace('"','').replace(',','') +'"');
          }
          csvContent.push(rowContent.join(","));
        }

        var dat = csvContent.join("\n");
        var encodedUri = encodeURI(dat);
        window.open(encodedUri);

Here's a fiddle.. when you run it it will ask you to open the file in Excel or whatever you use..

I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116