python创建doc表格,第一行加颜色 请示例
时间: 2024-02-19 22:02:55 浏览: 129
好的,下面是一个 Python 示例,用于创建一个带有颜色的 Word 表格。这个示例使用了 `python-docx` 库来创建和操作 Word 文档。
```python
from docx import Document
from docx.shared import RGBColor
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
# 创建一个 Word 文档
document = Document()
# 添加一个表格
table = document.add_table(rows=3, cols=3, style='Light List Accent 1')
table.alignment = WD_TABLE_ALIGNMENT.CENTER
# 设置第一行的颜色
for cell in table.rows[0].cells:
cell.fill.solid()
cell.fill.fore_color.rgb = RGBColor(0x27, 0x8e, 0xdb)
cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
# 设置第一行的内容
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'ID'
hdr_cells[1].text = 'Name'
hdr_cells[2].text = 'Age'
# 插入数据
records = [
(1, 'Alice', 25),
(2, 'Bob', 30),
(3, 'Charlie', 35)
]
for record in records:
row_cells = table.add_row().cells
row_cells[0].text = str(record[0])
row_cells[1].text = record[1]
row_cells[2].text = str(record[2])
# 保存文档
document.save('users.docx')
```
这个示例使用了 `python-docx` 库提供的方法来设置表格的样式和内容。它首先创建了一个带有三行三列的表格,然后设置了第一行的颜色和内容。最后,它插入了数据并保存了文档。
阅读全文
相关推荐
















