【Python】【python-docx講解】


參考:https://www.jianshu.com/p/8d8a75a50190

最近因項目需要,需從一個word文件中提取表格中的數據至另外一個word文件的表格中,每次操作都較為麻煩,所以寫了一段python代碼實現此功能,需要用到python-docx庫(pip install python-docx),下面將對其語法進行詳解。

1.需要導入的庫

from docx import Document(文檔讀寫)

from docx.shared import Pt (字體大小)

from docx.shared import Inches

from docx.oxml.ns import qn(設置字體格式)

from docx.shared import RGBColor (設置字體顏色)

from docx.enum.text import WD_ALIGN_PARAGRAPH (設置對其方式)

 

2.文檔讀取

doc=Document('文件路徑')  #打開word文檔

paras=doc.paragraphs   #獲取文件段落

tables=doc.tables   #獲取文件表格

table=tables[0]  #獲取第一個表格

table=tables[0].cell(1,2).text  #獲取表格1的第二行第三列的表格內容

—————獲取表格1的內容————

for row in table.rows:

for cell in row.cells:

    print(cell.text)

 

3.文檔操作

doc=Document() #創建一個空白文檔

p1=doc.add_paragraph()  #初始化建立一個自然段

p1.alignment=WD_ALIGN_PARAGRAPH.CENTER  #對齊方式為居中,沒有這句話默認左對齊

p1.paragraph_format.line_spacing=1.5  #設置該段落,行間距為1.5

p1.paragraph_format.first_line_indent=Inches(0.5)  #段落縮進0.5英寸

p1.paragraph_format.left_line_indent=Inches(0.5)  #設置左縮進0.5英寸

p1.paragraph_format.right_line_indent=Inches(0.5)  #設置右縮進0.5英寸

p1.space_after=Pt(5)  #設置段后距離為5

p1.space_before=Pt(5)  #設置段前距離為5

 

run1=p1.add_run(u'你好')   #寫入文本“你好”

run1.font.size=Pt(12)  #設置字體大小為12

run1.font.bold=True  #設置加粗

run1.italic=True  #設置斜體

 

para_heading1=doc.add_heading('',level=2)  #返回一個2級標題

run2=para_heading=para_heading.add_run(u'前言')  #添加二級標題前言

 

#添加圖片

doc.add_picture('照片路徑', width=Inches(1.25))

 

#增加表格

table=doc.add_table(rows=3, cols=3, style='Table Grid')  #創建一個33列的表格,樣式為黑色框

table.cell(0, 0).text=u'你好'  #添加第一行第一列內容為“你好”

table.cell(2,0).merge(table.cell(2,2))  #合並第三行第一列至第三列單元格

table.columns[

 

doc.save(D:\word.docx)  #保存文件在D盤,命名為word.docx

 

此方法雖然可以完成對段落的設置,但是每增加一個段落都要重新設置樣式,因此可以設置統一的標題,各個標題都可以采用,具體代碼如下所示:代碼中 "Normal"表示正文的樣式,["Heading 2"]表示2級標題的樣式,當然一級標題的樣式關鍵字為["Heading 1"],u代表后面字符串以 Unicode 格式 進行編碼,一般用在中文字符串前面,防止因為源碼儲存格式問題,導致再次使用時出現亂碼

 

doc=Document() #創建一個空白文檔

doc.styles["Normal"].font.name=u'Times New Roman'  #設置正文字體為Times New Roman

doc.styles["Normal"]._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')  #設置中文字體為宋體

上述兩句連用的含義是設置中文字體為宋體,西文字體為Times New Roman

doc.styles["Normal"].font.color.rgb=RGBColor(255,0,0) #設置正文全局顏色為紅色

doc.styles["Normal"].font.size=Pt(12) #設置字體大小為12

doc.styles["Heading 2"].font.size=Pt(20) #設置全局2級標題的字體大小為20

 

直接附上代碼

import os
from docx import Document
from docx.oxml.ns import qn
from docx.shared import Pt

class File_transfer_to_wordtable():
    """提取文件內容至新的word"""
    def __init__(self, file_path):
        self.file_path = file_path

    def tables(self):
        """讀取文件,獲取文件中的表格"""
        file_exist = os.path.exists(self.file_path)
        if file_exist:
            document=Document(self.file_path) #打開"文件"
            tables=document.tables  #獲取文件中的表格集
            return tables
        else:
            return "此文件不存在!"


    def new_document(self):
        """
        在新文件中新建表格,插入表頭
        """
        tables_num = len(self.tables())
        new_document = Document()  # 創建文檔對象
        new_document.styles["Normal"].font.size = Pt(7)
        new_document.styles['Normal'].font.name = 'Times New Roman'
        new_document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
        new_table = new_document.add_table(rows=tables_num-1, cols=6, style='Table Grid')

        new_table.cell(0, 0).text = u"序號"
        new_table.cell(0, 1).text = u"變更活動編號"
        new_table.cell(0, 2).text = u"需求和故障描述"
        new_table.cell(0, 3).text = u"涉及更改說明"
        new_table.cell(0, 4).text = u"更改波及影響分析"
        new_table.cell(0, 5).text = u"用例選取"

        """讀取變更說明中的第3個到最后一個表的內容"""
        for i in range(2, tables_num):
            table = self.tables()[i]
            cell_1 = table.cell(0, 1).text
            cell_2 = table.cell(1, 1).text
            cell_3 = table.cell(5, 1).text
            cell_4 = table.cell(6, 1).text
            cell_34 = "變更文件:"+ cell_3 +"\n"+ "變更模塊:" + cell_4
            cell_5 = table.cell(9, 1).text
            cell_6 = table.cell(11, 1).text

            """將表中內容填入另一個word中"""
            new_table.cell(i-1, 0).text = str(i-1)
            new_table.cell(i-1, 1).text = cell_1
            new_table.cell(i-1, 2).text = cell_2
            new_table.cell(i-1, 3).text = cell_34
            #若涉及到的測試用例為空,則寫入無
            if cell_5 == "":
                new_table.cell(i-1, 4).text = "無"
            else:
                new_table.cell(i-1, 4).text = cell_5
            new_table.cell(i-1, 5).text = cell_6

        """保存word文檔"""
        new_document.save("D:\\file\word.docx")

#創建實例 word=File_transfer_to_wordtable("D:\\file\xxx.docx") print(word.tables()) word.new_document()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM