71

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

1
  • 2
    You can generate a CSV download from Javascript with HTML 5 in some browsers: see accepted answer to stackoverflow.com/questions/17836273/… Commented Jul 24, 2013 at 15:06

5 Answers 5

52

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".

Sign up to request clarification or add additional context in comments.

4 Comments

In 2015, there are more libraries like ng-xlsx and js-xlsx
In end 2016 there is a very good library github.com/guyonroche/exceljs (i tried Excel Builder but there is a really issue while you are trying to save your file)
Excel Builder (.js) is no longer maintained. There is also no documentation for it as the website gone off.
excelbuilderjs.com/index.html link no longer works as well.
37

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');

1 Comment

PHPExcel is deprecated and suggests you use PhpSpreadsheet instead.
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> 

6 Comments

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.
@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 example.
i tried this library but it's unsafe in chromeextension.
@gumuruh is there some specific plugin/extension you used to check? I couldn't find any way of checking this plugin's safety.
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?
|
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.

1 Comment

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?
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>

2 Comments

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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.