69

Is there any way to generate Excel/CSV through Javascript? (It should be browser compaatible too)

Pikamander2
  • 7,332
  • 3
  • 48
  • 69
Chinmay
  • 4,971
  • 5
  • 23
  • 15
  • 2
    You can generate a CSV download from Javascript with HTML 5 in some browsers: see accepted answer to http://stackoverflow.com/questions/17836273/directly-output-javascript-calculations-as-csv-for-download-without-further-serv/17836529?noredirect=1#comment26036496_17836529 – Paul Jul 24 '13 at 15:06

5 Answers5

53

There is an interesting project on github called Excel Builder (.js) that offers a client-side way of downloading Excel xlsx files and includes options for formatting the Excel spreadsheet.
https://github.com/stephenliberty/excel-builder.js

You may encounter both browser and Excel compatibility issues using this library, but under the right conditions, it may be quite useful.

Another github project with less Excel options but less worries about Excel compatibility issues can be found here: ExcellentExport.js
https://github.com/jmaister/excellentexport

If you are using AngularJS, there is ng-csv:
a "Simple directive that turns arrays and objects into downloadable CSV files".

mg1075
  • 17,985
  • 8
  • 59
  • 100
35

If you can generate the Excel file on the server, that is probably the best way. With Excel you can add formatting and get the output to look better. Several Excel options have already been mentioned. If you have a PHP backend, you might consider phpExcel.

If you are trying to do everything on the client in javascript, I don't think Excel is an option. You could create a CSV file and create a data URL to allow the user to download it.

I created a JSFiddle to demonstrate: http://jsfiddle.net/5KRf6/3/

This javascript (assuming you are using jQuery) will take the values out of input boxes in a table and build a CSV formatted string:

var csv = "";
$("table").find("tr").each(function () {
    var sep = "";
    $(this).find("input").each(function () {
        csv += sep + $(this).val();
        sep = ",";
    });
    csv += "\n";
});

If you wish, you can drop the data into a tag on the page (in my case a tag with an id of "csv"):

$("#csv").text(csv);

You can generate a URL to that text with this code:

window.URL = window.URL || window.webkiURL;
var blob = new Blob([csv]);
var blobURL = window.URL.createObjectURL(blob);

Finally, this will add a link to download that data:

$("#downloadLink").html("");
$("<a></a>").
attr("href", blobURL).
attr("download", "data.csv").
text("Download Data").
appendTo('#downloadLink');
MattBianco
  • 1,501
  • 2
  • 20
  • 30
digitaleagle
  • 854
  • 1
  • 9
  • 15
10

Similar answer posted here.

Link for working example

var sheet_1_data = [{Col_One:1, Col_Two:11}, {Col_One:2, Col_Two:22}];
var sheet_2_data = [{Col_One:10, Col_Two:110}, {Col_One:20, Col_Two:220}];
var opts = [{sheetid:'Sheet One',header:true},{sheetid:'Sheet Two',header:false}];
var result = alasql('SELECT * INTO XLSX("sample_file.xlsx",?) FROM ?', [opts,[sheet_1_data ,sheet_2_data]]);

Main libraries required -

<script src="http://alasql.org/console/alasql.min.js"></script> 
<script src="http://alasql.org/console/xlsx.core.min.js"></script> 
  • 1
    Hey which line is to save the excel file? Because right now I have an array and I wanted to write the array into excel spread sheet. – QWERTY Aug 26 '17 at 08:09
  • @DeniseTan, the save functionaity is handled by `alasql` which gets trigerred after generating the file. Your data needs to be in array of objects (see my example). Object key is necessary to defined column name. You can convert your array to array of objects. Look at [this](https://stackoverflow.com/questions/20807804/convert-an-array-to-an-array-of-objects) example. – Sujit Kumar Singh Aug 26 '17 at 10:41
  • i tried this library but it's unsafe in chromeextension. – gumuruh Sep 30 '19 at 02:57
  • @gumuruh is there some specific plugin/extension you used to check? I couldn't find any way of checking this plugin's safety. – Sujit Kumar Singh Sep 30 '19 at 11:20
  • 1
    no i mean when we're implementing some external javascript into ChromeExtension tool, we need to ensure there's no eval statement, and we must embed all the js file inside our project without any external dependencies.... Aaargh, anyway,... you may know once you're developing a ChromeExtension tool. ok @SujitKumarSingh, ok? – gumuruh Sep 30 '19 at 14:43
  • @gumuruh got it. I wasn't aware about this, thanks for this information. – Sujit Kumar Singh Oct 01 '19 at 04:55
2

Create an AJAX postback method which writes a CSV file to your webserver and returns the url.. Set a hidden IFrame in the browser to the location of the CSV file on the server.

Your user will then be presented with the CSV download link.

  • 4
    Kinda silly though - passing data back to the server just so that it can serve it right back to the user. Also, the generated XLS might be rather large. (perhaps that's why the author wants to generate it client-side?) Maybe then it's better to generate the XLS server-side too? – Vilx- Dec 02 '08 at 14:19
1

To answer your question with a working example:

<script type="text/javascript">
function DownloadJSON2CSV(objArray)
{
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = new Array();

        for (var index in array[i]) {
           line.push('"' + array[i][index] + '"');
        }

        str += line.join(';');
        str += '\r\n';
    }
    window.open( "data:text/csv;charset=utf-8," + encodeURIComponent(str));
}
</script>
Fireworm
  • 189
  • 2
  • 2
  • 14
  • 2
    The only drawback is that you can't decide what the file is called. You'll have to rely on the user to save it as *.csv, if they want to open it easily. – Fireworm May 21 '13 at 07:31
  • In my case, this downside is not a problem as my client wants it as a feature because I am doing it for his admin dashboard. Thank anyways for the answer. – Syed M. Sannan Jan 07 '22 at 11:10