Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build XLSX File With JavaScript

I'm trying to build out an XLSX file using JavaScript using some database query results. I have to use JavaScript as the server back end only provides a JavaScript interface to work with (and it doesn't like jQuery). Now, I seem to have uncovered something to actually create the base64 encoded data to write to the file (the server interface provides an API for creating files using base64 encoded strings and defining a file type). XLSX.js looks like it will work well for that purpose, since it looks like it can read in some form of JS object and convert it to a base64 string. However, I am rather unclear about how to generate the worksheet XML data in the first place, or how I would want to construct a representative JS object. The only useful information I can seem to find doesn't really give me a good idea how to build it out, if I can even locate information on structuring. Most I find is about reading the files, not creating them. Also, I thought I found some simple to implement methods, but then they devolve into a mess of libraries and I get lost trying to understand which files are actually necessary and how to correctly include them in the work.

like image 653
Michael McCauley Avatar asked Apr 23 '26 10:04

Michael McCauley


1 Answers

You can export data from js to XLS, XLSX and CSV formats with Alasql library.

For example we want to write a data which we saved in test variable in an XLSX file through click a button. To do this just use following steps:

1- Include following files in your page:

 <script src="http://alasql.org/console/alasql.min.js"></script> 
 <script src="http://alasql.org/console/xlsx.core.min.js"></script> 

2- So Then make a function in controller to save the test array as a xlsx file:

function saveAsXlsx(){
   alasql('SELECT * INTO XLSX("output.xlsx",{headers:true}) FROM ?',[test]);
}

So We save the data which we had in variable test into a file which we named it output.xlsx here.

3- The last part is the easiest part. Run the function on click on a button:

 <button onclick="saveAsXlsx()" >Save as XLSX</button>
like image 95
Iman Sedighi Avatar answered Apr 26 '26 00:04

Iman Sedighi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!