Is there any way to generate Excel/CSV through Javascript? (It should be browser compaatible too)
An Excel add-in interacts with objects in Excel by using the Office JavaScript API, which includes two JavaScript object models: Excel JavaScript API: Introduced with Office 2016, the Excel JavaScript API provides strongly-typed objects that you can use to access worksheets, ranges, tables, charts, and more.
This can be done quite easily using SheetJS. import { read, writeFileXLSX, utils } from "https://cdn.sheetjs.com/xlsx-0.18.7/package/xlsx.mjs"; const workbook = read(data, { type:'binary', }); data is the binary string resulting from reading an Excel file as a binary string with the FileReader API.
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".
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With