|
发表于 2023-7-6 09:56:46
|
显示全部楼层
本楼为最佳答案
要设置Word表格中单元格的居中对齐,可以使用paragraph.alignment属性来设置单元格内文本的对齐方式。以下是修改后的代码:
- python
- from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
- def get_table():
- t2 = document.add_table(rows=1, cols=4)
- t2.style = 'Table Grid'
- t2.autofit = True
- hdr_cells = t2.rows[0].cells
-
- # 设置表头
- hdr_cells[0].text = '运营指标'
- hdr_cells[1].text = '本周受理量'
- hdr_cells[2].text = '上周受理量'
- hdr_cells[3].text = '本月累计'
-
- # 导入数据
- df = pandas.read_excel(file_path + "周报.xlsx", '南一', dtype=str, keep_default_na='')
-
- # 读取内容(每一行是一个列表)
- for d in df.values.tolist():
- for row1, row2, row3, row4 in [d]:
- row_cells = t2.add_row().cells
- row_cells[0].text = row1
- row_cells[1].text = row2
- row_cells[2].text = row3
- row_cells[3].text = row4
-
- # 设置单元格内文本居中对齐
- for cell in row_cells:
- for paragraph in cell.paragraphs:
- paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
复制代码
在修改后的代码中,我们使用WD_PARAGRAPH_ALIGNMENT.CENTER来设置单元格内文本的居中对齐方式。遍历每个单元格的段落,并将其对齐方式设置为居中对齐。
希望这可以帮助到您!如果还有其他疑问,请随时向我提问。 |
|