使用HTML和JavaScript创建Excel格式输出

Create Excel Format Output using HTML and JavaScript

本文关键字:Excel 格式 输出 创建 JavaScript HTML 使用      更新时间:2023-09-26

我接受了面试,问的问题是:

编写一个JS插件,可以将单元格和值作为输入,并在浏览器上呈现excel格式的输出。例如,

给定输入(单元格和值):

J3 = 5
A2 = 20
K1 = 10

浏览器上的输出应为excel格式

   A   B   C ....... J    K .......
1                         10
2  20 
3                    5
..

我在为这个问题寻找正确的解决方案。

我试着解决这个问题(写psudeo代码)

var  cell = {"J3": 5, "A2":20, "K1": 10}
// Function they will call for generate excel style table
generateExcel(cell, selector) {     
1.  create blank table  which has A-Z column (with selector as A-Z resp) and 1 to 100 rows (with selector as 1 to 100 resp)
2. Loop through each cell and for each cell
  2.1 find the column (J) and row (3)
  2.2 Add/replace value in that TD
3. Once all the information from cell in enter in table,  print the table in the document at given selector        

}

他们说,对于大量的细胞输入来说,这是无效的。我建议我们可以使用矩阵创建表

   A   B...    J  K .... 
1 [               10      ]
2   20
3              5   

我认为你开局不错。首先创建一个包含元素的表。这将是26列宽,与最大的y值一样高。把字母转换成数字。

很抱歉有w3schools链接,我很容易因为提到它们而被否决,但它们在表对象上有最好的文档,我可以为你搜索。如果有人有更好的东西,我会更新它。

http://www.w3schools.com/jsref/dom_obj_table.asp

MDN教程

https://developer.mozilla.org/en/Traversing_an_HTML_table_with_JavaScript_and_DOM_Interfaces

然后,您可以通过最有效地访问表格单元格

var table = ;//get by id or create element, not sure what they expect
table.rows[y].cells[x].appendChild(...);

Excel电子表格是表格。你能用一张简单的桌子吗?如果是这样的话,我建议使用CSS border-collapse属性,使其看起来更好,同时可能减少单元格填充和边距。