1,、打開一個doc文檔
from docx import Document doc = Document(file_path)
2,、新建一個doc文檔
3、設(shè)置doc文檔格式
doc.styles['Normal'].font.name = u'Times New Roman' doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體') style = doc.styles['Normal'] paragraph_format = style.paragraph_format paragraph_format.first_line_indent = Cm(0.74) # 設(shè)置1級標(biāo)題的字體為Times New Roman,, 且無縮進(jìn) # 這種寫法只能夠修改Normal樣式的字體,修改標(biāo)題的字體無效,。 style_heading1 = doc.styles['Heading 1'] style_heading1.font.name = u'Times New Roman' heading1_format = style_heading1.paragraph_format heading1_format.first_line_indent = Cm(0) # 設(shè)置2級標(biāo)題的字體為Times New Roman,, 且無縮進(jìn) style_heading2 = doc.styles['Heading 2'] style_heading2.font.name = 'Times New Roman' heading2_format = style_heading2.paragraph_format heading2_format.first_line_indent = Cm(0)
4、向docx文檔寫入內(nèi)容
doc.add_heading(dashboard, 1) doc.add_heading(visualization, 2) doc.add_paragraph('該visualization的類型為' + visualization_type + ',其作用是' + description + ',。其界面如下圖所示:', style='Body Text') # 指定圖片寬度為 4英寸, 圖片高度會自動調(diào)整 doc.add_picture(pic_path, width=Inches(4)) last_paragraph = doc.paragraphs[-1] last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER doc.save('resource/output.docx')
2,、獲取 paragraph的內(nèi)容, doc.paragrashs是一個列表,,遍歷列表分別獲取每一個段落的內(nèi)容:
for j, paragraph in enumerate(doc.paragraphs): para_text = paragraph.text
標(biāo)題也屬于doc.paragrashs列表,。
判斷某個段落是否是標(biāo)題:
paragraph.style.name == 'Heading 3'
|