FileName_Save = "修改后.docx" print('正在处理:' + fileName) document = docx.Document(fileName) # 修改表格格式 temp_i_row = 0 for i_index, i_table in enumerate(document.tables): # 设置表格外边框为 1.5 磅 tblPr = i_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 i_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(FileName_Save) 报错:AttributeError: 'CT_TcPr' object has no attribute 'tcBorders'
时间: 2024-04-21 10:27:10 浏览: 191
这个报错的原因是因为在修改表格内边框的时候,代码中使用了 `cell._element.tcPr.tcBorders`,而实际上 `CT_TcPr` 对象并没有 `tcBorders` 这个属性。你可以尝试修改这个属性为 `tcBorders` 的正确名称,比如 `tcBorders` 修改为 `tcMar`。修改后的代码如下:
```
FileName_Save = "修改后.docx"
print('正在处理:' + fileName)
document = docx.Document(fileName)
# 修改表格格式
temp_i_row = 0
for i_index, i_table in enumerate(document.tables):
# 设置表格外边框为 1.5 磅
tblPr = i_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 i_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.tcMar.set(qn('w:insideH'), 'single')
cell._element.tcPr.tcMar.set(qn('w:insideV'), 'single')
cell._element.tcPr.tcMar.set(qn('w:top'), 'single')
cell._element.tcPr.tcMar.set(qn('w:bottom'), 'single')
cell._element.tcPr.tcMar.set(qn('w:left'), 'single')
cell._element.tcPr.tcMar.set(qn('w:right'), 'single')
cell._element.tcPr.tcMar.set(qn('w:sz'), '18')
cell._element.tcPr.tcMar.set(qn('w:val'), 'single')
cell._element.tcPr.tcMar.set(qn('w:space'), '0')
# 保存文档
document.save(FileName_Save)
```
这样应该就可以解决这个报错了。
阅读全文