Python-Word文件快速編輯
1、需要裝Python庫python-docx;
2、想docx中新增文字;
from docx import Document
doc = Document()
doc.add_heading('iiiiiii')
doc.add_paragraph('ppppppppppppppppppp')
3、文字樣式修改;
from docx import Document
from docx.enum.style import WD_STYLE_TYPE
doc2 = Document()
for s in doc2.styles:
if s.type == WD_STYLE_TYPE.PARAGRAPH:
print(s.name)
doc2.add_heading('一級標題', level = 1)
doc2.add_heading('大標題', level = 0)
doc2.add_paragraph('副標題', 'Subtitle')
doc2.save()
4、段落對齊方式
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
doc3 = Document()
p1 = doc3.add_paragraph('測試左對齊')
p1.alignment = WD_ALIGN_PARAGRAPH.LEFT
p2 = doc3.add_paragraph('測試居中')
p1.alignment = WD_ALIGN_PARAGRAPH.CENTER
doc3.save('hhhhh.docx')
5、字型樣式
from docx import Document
from docx.shared import Pt
doc4 = Document()
p = doc4.add_paragraph('kkkkkk')
p1 = p.add_run('給這幾個字修改樣式')
p1.font.bold = True
p1.font.size = Pt(20)
doc4.save('doc4.docx')
6、新增圖片
from docx import Document
doc5 = Document()
doc5.add_picture('picname.png')
7、新增表格
from docx import Document
from docx.enum.sytle import WD_STYLE_TYPE
doc6 = Document()
table1 = doc6.add_table(rows = 3, cols= 8)
table1.style = 'Light Grid Accent 3'
cell = table1.cell(0,0)
cell.text = ('這裡是左上角00位置')
doc6.save('doc6.docx')