动态生成表格用类封装
时间: 2023-07-25 19:24:07 浏览: 57
好的,生成表格可以使用 HTML 的 table 标签实现。下面是一个示例代码:
```python
class Table:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.table = []
def create_table(self):
for i in range(self.rows):
row = []
for j in range(self.cols):
row.append('')
self.table.append(row)
def set_value(self, row_idx, col_idx, value):
self.table[row_idx][col_idx] = value
def get_html(self):
html = '<table>'
for row in self.table:
html += '<tr>'
for col in row:
html += f'<td>{col}</td>'
html += '</tr>'
html += '</table>'
return html
```
使用示例:
```python
table = Table(3, 2)
table.create_table()
table.set_value(0, 0, 'A')
table.set_value(0, 1, 'B')
table.set_value(1, 0, 'C')
table.set_value(1, 1, 'D')
table.set_value(2, 0, 'E')
table.set_value(2, 1, 'F')
print(table.get_html())
```
输出结果:
```html
<table>
<tr>
<td>A</td>
<td>B</td>
</tr>
<tr>
<td>C</td>
<td>D</td>
</tr>
<tr>
<td>E</td>
<td>F</td>
</tr>
</table>
```
通过 Table 类,我们可以动态生成任意行数和列数的表格,并可以设置单元格的值。最后,调用 get_html 方法即可得到表格的 HTML 代码。