网上找了许多都不好使,需要收费,以下的好使
from docx import Document
from docx.oxml.ns import qn
from docx.oxml import OxmlElement
def set_table_width_to_percentage(docx_path, percentage):
doc = Document(docx_path)
for table in doc.tables:
tblPr = table._tbl.tblPr
if len(tblPr) == 0: # 修正此处的判断条件
tblPr = OxmlElement('w:tblPr')
table._tbl.append(tblPr)
tblWidth = OxmlElement('w:tblW')
tblWidth.set(qn('w:w'), str(int(590 * percentage / 100)))
tblWidth.set(qn('w:type'), 'pct')
tblPr.append(tblWidth)
doc.save(docx_path)
docx_path = "test.docx" # 替换为实际的 Word 文件路径
# 847是99.9%百分比 ,自己调试自己想要比例,因为涉及单位转换
percentage = 847 # 这里设置您想要的百分比,例如 80%
set_table_width_to_percentage(docx_path, percentage)