1、打開一個doc文檔
- import docx
- from docx import Document
- doc = Document(file_path)
2、新建一個doc文檔
- # 新建doc文檔
- doc = docx.Document()
3、設置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
- # 首行縮進0.74厘米,即2個字符
- paragraph_format.first_line_indent = Cm(0.74)
- # 設置1級標題的字體為Times New Roman, 且無縮進
- # 這種寫法只能夠修改Normal樣式的字體,修改標題的字體無效。
- 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)
- # 設置2級標題的字體為Times New Roman, 且無縮進
- 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文檔寫入內容
- # 寫入一級標題
- doc.add_heading(dashboard, 1)
- # 寫入二級標題
- doc.add_heading(visualization, 2)
- # 寫入 段落文字
- doc.add_paragraph('該visualization的類型為' + visualization_type + ',其作用是' + description + '。其界面如下圖所示:', style='Body Text')
- # 寫入圖片
- # 指定圖片寬度為 4英寸, 圖片高度會自動調整
- 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的內容, doc.paragrashs是一個列表,遍歷列表分別獲取每一個段落的內容:
- for j, paragraph in enumerate(doc.paragraphs):
- para_text = paragraph.text
標題也屬于doc.paragrashs列表。
判斷某個段落是否是標題:
paragraph.style.name == 'Heading 3'