问题背景
在用docx模块创建表格时想用自定义函数统一设置表格属性,但是调用时代码不执行
代码
# 这是调用函数时的代码
from docx import Document
from Eastmoney import Buit_table
doc = Document()
table = Buit_table
table_1 = table.add_table(3, 5)
doc.save('test.docx')
# 这是函数代码
def add_tables(row, col):
from docx import Document
from docx.shared import Pt
from docx.shared import Cm
from docx.shared import RGBColor
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
doc_table = Document()
table = doc_table.add_table(rows=row, cols=col, style='Table Grid') # 添加表格
table.style.paragraph_format.alignment = WD_TABLE_ALIGNMENT.CENTER # 水平居中
for row in range(row): # 为每一列设置居中
for col in range(col):
cell = table.cell(row, col)
pa = cell.paragraphs[0]
pa.alignment = WD_TABLE_ALIGNMENT.CENTER
cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER # 垂直居中
return table
运行结果
运行后只生成了一个空白的word,表格没有添加进去,程序没报错,初学python,不知道问题出在哪里