|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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
我现在写成了这个样子,能够把EXCEL数据表插入到WORD中,但是每列单元格内文本默认是左对齐的。请问大佬们,怎么改成居中对齐?
要设置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来设置单元格内文本的居中对齐方式。遍历每个单元格的段落,并将其对齐方式设置为居中对齐。
希望这可以帮助到您!如果还有其他疑问,请随时向我提问。
|
|