使用JavaScript构建XLSX文件 [英] Build XLSX File With JavaScript

查看:130
本文介绍了使用JavaScript构建XLSX文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些数据库查询结果使用JavaScript构建一个XLSX文件。我必须使用JavaScript作为服务器后端只提供一个JavaScript接口来处理(并且它不喜欢jQuery)。现在,我似乎已经发现了一些实际创建base64编码数据来写入文件的东西(服务器界面提供了使用base64编码字符串创建文件并定义文件类型的API)。 XLSX.js看起来像这样可以很好地工作,因为它看起来像是可以以某种形式的JS对象读取并将其转换为base64字符串。但是,我不清楚如何首先生成工作表XML数据,或者如何构建一个代表性的JS对象。我似乎找到的唯一有用的信息并不真的给我一个好主意,如何建立它,如果我甚至可以找到有关结构的信息。大多数我发现是关于阅读文件,而不是创建它们。另外,我以为我发现一些简单的实现方法,但是后来他们掉进了一堆图书馆,我失去了尝试了解哪些文件实际上是必要的,以及如何正确地将它们包含在工作中。

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.

推荐答案

您可以使用 Alasql 库。

例如,我们要通过点击一个按钮将我们保存在测试变量中的数据写入XLSX文件。要执行此操作只需使用以下步骤:

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-在页面中包含以下文件:

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]);
}

所以我们将我们在变量测试中的数据保存到一个文件中在这里命名为output.xlsx。

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

3-最后一部分是最简单的部分。运行功能点击按钮:

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

 <button onclick="saveAsXlsx()" >Save as XLSX</button>

这篇关于使用JavaScript构建XLSX文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆