Python-docx库 设置word已存在的表格外面边框1.5磅,里面边框0.75磅
时间: 2024-03-15 19:44:30 浏览: 120
要设置一个已经存在的表格的边框,你需要使用 `python-docx` 库的 `Table` 类。以下是设置表格外边框为 1.5 磅,内边框为 0.75 磅的代码示例:
```python
from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.enum.text import WD_LINE_SPACING
from docx.shared import Pt
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
# 打开已存在的 Word 文档
document = Document('existing_doc.docx')
# 获取第一个表格
table = document.tables[0]
# 设置表格外边框为 1.5 磅
tblPr = table._element.xpath('w:tblPr')[0]
tblBorders = OxmlElement('w:tblBorders')
tblBorders.set(qn('w:top'), 'on')
tblBorders.set(qn('w:left'), 'on')
tblBorders.set(qn('w:bottom'), 'on')
tblBorders.set(qn('w:right'), 'on')
tblBorders.set(qn('w:insideH'), 'on')
tblBorders.set(qn('w:insideV'), 'on')
tblBorders.set(qn('w:sz'), '24')
tblBorders.set(qn('w:val'), 'single')
tblBorders.set(qn('w:space'), '0')
tblPr.append(tblBorders)
# 设置表格内边框为 0.75 磅
for row in table.rows:
for cell in row.cells:
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.font.size = Pt(10)
cell._element.tcPr.tcBorders.set(qn('w:insideH'), 'single')
cell._element.tcPr.tcBorders.set(qn('w:insideV'), 'single')
cell._element.tcPr.tcBorders.set(qn('w:top'), 'single')
cell._element.tcPr.tcBorders.set(qn('w:bottom'), 'single')
cell._element.tcPr.tcBorders.set(qn('w:left'), 'single')
cell._element.tcPr.tcBorders.set(qn('w:right'), 'single')
cell._element.tcPr.tcBorders.set(qn('w:sz'), '18')
cell._element.tcPr.tcBorders.set(qn('w:val'), 'single')
cell._element.tcPr.tcBorders.set(qn('w:space'), '0')
# 保存文档
document.save('existing_doc.docx')
```
注意:上述代码只是一个示例,具体实现可能需要根据你的 Word 文档的结构进行调整。
阅读全文