python修改docx文档的表格内中文字体
生活随笔
收集整理的這篇文章主要介紹了
python修改docx文档的表格内中文字体
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
from docx import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Cm,Pt
from docx.oxml.ns import qndocument = Document('2.docx')#讀取文檔的第一個表格數據
tables = document.tables[0]#在第該表格3行1列的單元格內輸入“能幾日又中秋?as12A”
run = tables.cell(2,0).paragraphs[0].add_run(u'能幾日又中秋?as12A')#輸入時默認華文琥珀字體
run.font.name = '華文琥珀'
#輸入字體大小默認30號
run.font.size = Pt(30)r = run._element
#將輸入語句中的中文部分字體變為華文行楷
r.rPr.rFonts.set(qn('w:eastAsia'), '華文行楷')#居中
tables.cell(1,0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER#保存
document.save('3.docx')
要點:
1、在同一個 單元格內連續使用 ?table.cell.paragraphs[0].add_run('XXX'),則默認為在單元格中附加文字,而非在該單元格內重建。
2、如果沒有這兩句,則無法改變單元格內的中文字體:
r = run._element
r.rPr.rFonts.set(qn('w:eastAsia'), '黑體')
3、run.font.name = '黑體' ?
上述語句只能修改ascii 代碼所包含的字符, 中文不可顯示。
綜合演示:
代碼:
from docx import Document from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.shared import Cm,Pt from docx.oxml.ns import qndocument = Document('2.docx') tables = document.tables[0]run = tables.cell(1,0).paragraphs[0].add_run(u'二十年重過南樓hellow,233') run.font.name = '仿宋' run.font.size = Pt(18) r = run._element r.rPr.rFonts.set(qn('w:eastAsia'), '仿宋') tables.cell(1,0).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTERrun = tables.cell(1,0).paragraphs[0].add_run(u'柳下系船猶未穩as12A') run.font.name = '黑體' run.font.size = Pt(35) r = run._element r.rPr.rFonts.set(qn('w:eastAsia'), '黑體')run = tables.cell(2,0).paragraphs[0].add_run(u'能幾日又中秋?as12A') run.font.name = '華文琥珀' run.font.size = Pt(30) r = run._element r.rPr.rFonts.set(qn('w:eastAsia'), '華文行楷')document.save('3.docx')運行后結果:
總結
以上是生活随笔為你收集整理的python修改docx文档的表格内中文字体的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab彩色图添加水印,基于离散小波
- 下一篇: IMU: 惯性测量传感器