072-python庫(kù)docx

一、前記

需要操作word文檔,讀取,寫(xiě)入等。

實(shí)例:

from docx import Document
document = Document(needPath)
tables = document.tables
for k in range(0, len(tables)):
  table = tables[k]
  for j in range(1, len(table.rows)):
    resultTemp = table.cell(j,3).text

Python Dox是一個(gè)用于創(chuàng)建和更新微軟Word(.DOX)文件的Python庫(kù)。python-docx包,這是一個(gè)很強(qiáng)大的包,可以用來(lái)創(chuàng)建docx文檔,包含段落、分頁(yè)符、表格、圖片、標(biāo)題、樣式等幾乎所有的word文檔中能常用的功能都包含了,這個(gè)包的主要功能便是用來(lái)創(chuàng)建文檔,相對(duì)來(lái)說(shuō)用來(lái)修改功能不是很強(qiáng)大。

Python Dox允許您創(chuàng)建新文檔,并對(duì)現(xiàn)有文檔進(jìn)行更改。實(shí)際上,它只允許您對(duì)現(xiàn)有文檔進(jìn)行更改;只是從一個(gè)沒(méi)有任何內(nèi)容的文檔開(kāi)始,它可能首先感覺(jué)像是從頭開(kāi)始創(chuàng)建一個(gè)文檔。這個(gè)特點(diǎn)是強(qiáng)有力的。文檔的外觀(guān)是由刪除所有內(nèi)容時(shí)留下的部分決定的。樣式和頁(yè)眉和頁(yè)腳等內(nèi)容與主內(nèi)容分開(kāi),允許您在開(kāi)始文檔中放置大量自定義,然后出現(xiàn)在所生成的文檔中。讓我們一步一步地創(chuàng)建一個(gè)文檔一個(gè)例子,從文檔中可以做的兩件事開(kāi)始,打開(kāi)它并保存它。

二、安裝

pip install python-docx

三、應(yīng)用

打開(kāi)及保存文件:

from docx import Document
document = Document('test.docx')
document.save('test.docx')

添加文本:

document.add_paragraph('test text')

調(diào)整文本位置格式為居中:

from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
document = Document('test.docx')
paragraph = document.add_paragraph('123')
paragraph.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER
document.save('test.docx')

調(diào)整左縮進(jìn)0.3英寸:

document = Document('test.docx')
paragraph = document.add_paragraph('this is test for left_indent with inches')
paragraph_format = paragraph.paragraph_format
paragraph_format.left_indent = Inches(0.3)
document.save('test.docx')

首行縮進(jìn):

paragraph_format.first_line_indent = Inches(0.3)

上行間距:

paragraph_format.space_before = Pt(18)

下行間距:

paragraph_format.space_after = Pt(12)

行距:

paragraph_format.line_spacing = Pt(18)

分頁(yè)格式:

緊跟上段:

paragraph_format.keep_together

若本頁(yè)無(wú)法完全顯示,另起一頁(yè):

paragraph_format.keep_with_next

字體格式:

p = document.add_paragraph()
run = p.add_run('test typeface')
#加粗
run.font.bold = True
#斜體
run.font.italic = True
#下劃線(xiàn)
run.font.underline = True

WD_UNDERLINE 中有所有下劃線(xiàn)格式

調(diào)用樣例:

run.underline = WD_UNDERLINE.DOT_DASH

字體顏色:

from docx.shared import RGBColor
test = document.add_paragraph().add_run('color')
font = test.font
font.color.rgb = RGBColor(0x42, 0x24 , 0xE9)

調(diào)用預(yù)設(shè)顏色:

from docx.enum.dml import MSO_THEME_COLOR
font.color.theme_color = MSO_THEME_COLOR.ACCENT_1

四、一個(gè)不錯(cuò)的例子

# -*- coding: utf-8 -*-
'''
Created on 2018年9月24日

@author: 362409100
'''

import os
import sys

from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.table import WD_ALIGN_VERTICAL, WD_ROW_HEIGHT_RULE
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_BREAK
from docx.oxml.ns import qn
from docx.shared import Inches, Pt, RGBColor

global doc
global last_err
last_err = ""

#sys.path.append('..\\Lib\\site-packages')

def Init():
    global doc
    doc = Document()
    doc.styles["Normal"].font.name = u'宋體'
    doc.styles["Normal"].font.size = Pt(8)
    doc.styles["Normal"]._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
    head = doc.add_heading("", level=1)
    run = head.add_run(u"社會(huì)主義核心價(jià)值觀(guān)")
    run.font.size = Pt(20)
    run.font.color.rgb = RGBColor(128, 0, 0)
    run.font.name = u"宋體"
    run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
    head.alignment = WD_ALIGN_PARAGRAPH.CENTER

def Save(dst):
    global doc
    global last_err
    try:
        doc.save(dst)
        return True
    except IOError as e:
        last_err = e.strerror
        return False

def AddLineTitle(title):
    global doc
    head = doc.add_heading("", level=2)
    run = head.add_run(title)
    run.font.size = Pt(16)
    run.font.color.rgb = RGBColor(0, 0, 0)
    run.font.name = u"宋體"
    run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')

def AddInfoTitle(title):
    global doc
    head = doc.add_heading("", level=3)
    run = head.add_run(title)
    run.font.size = Pt(12)
    run.font.color.rgb = RGBColor(0, 0, 0)
    run.font.name = u"宋體"
    run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')

def AddLineText(text):
    global doc
    p = doc.add_paragraph()
    run = p.add_run(text)
    run.font.size = Pt(8)
    run.font.name = u"宋體"
    run._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')

def AddRecord(qj, cj, gh, mc, lx, ms, bz, tp):
    global doc
    table = doc.add_table(6, 2)
    table.style = "Table Grid"   # The First Table Style Of The MS Word

    for row in table.rows:
        row.height = Pt(14)
        row.height_rule = WD_ROW_HEIGHT_RULE.EXACTLY
    table.rows[-1].height_rule = WD_ROW_HEIGHT_RULE.AUTO  # The Last Row Contains A Picture
    table.cell(0, 0).text = qj
    table.cell(0, 1).text = cj
    table.cell(0, 0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    table.cell(0, 1).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    table.cell(1, 0).text = gh
    table.cell(1, 1).text = mc
    table.cell(1, 0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    table.cell(1, 1).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    table.cell(2, 0).text = lx
    table.cell(2, 1).text = ms
    table.cell(2, 0).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    table.cell(2, 1).vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    item = table.cell(3, 0).merge(table.cell(3, 1))
    item.text = bz
    item.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    item = table.cell(4, 0).merge(table.cell(4, 1))
    item.text = u"富強(qiáng)民主文明和諧愛(ài)國(guó)敬業(yè)誠(chéng)信友善自由平等公正法治:"
    item.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
    item = table.cell(5, 0).merge(table.cell(5, 1))
    p = item.paragraphs[0]
    p.add_run().add_picture(tp, Pt(300), Pt(300))
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER

def GetLastError():
    global last_err
    return last_err


def Test():
    path = os.path.split(os.path.realpath(__file__))[0]
    file = path + "\\word.docx"

    Init()
    AddLineTitle(u"富強(qiáng)民主")
    AddInfoTitle(u"一、文明和諧")
    AddLineText(u"愛(ài)國(guó)敬業(yè)")
    AddRecord(u"誠(chéng)信", u"友善", u"自由", u"平等", u"公正",
              u"法治", u"社會(huì)主義核心價(jià)值觀(guān)", "2.jpg")
    Save(file)

Test()
print(GetLastError())
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容