日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python 第三方库之docx

發(fā)布時(shí)間:2023/12/20 python 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python 第三方库之docx 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

日常上官網(wǎng)?https://python-docx.readthedocs.io/en/latest/

一、安裝

pip install python-docx

二、寫入word

word 中主要有兩種用文本格式等級:塊等級(block-level)和內(nèi)聯(lián)等級(inline-level)word 中大部分內(nèi)容都是由這兩種等級的對象組成的(其他的諸如眉頁、引腳等,docx 庫的作者還在開發(fā)中)

塊等級(block-level):也就是段落

塊對象一般包括:段落(paragraph)、圖片(inline picture)、表(table)、標(biāo)題(heading)、有序列表(numbered lists)、無序列表(bullets?lists)

段落是 word 文件中的主要塊對象(block-level object),塊等級項(xiàng)(block-level item)主要任務(wù)是將文本格式從左邊界向右邊界展示(flows);對于段落而言,邊界就是分段標(biāo)識,或者是文本的列邊界,列表(table)也是塊對象(block-level object)

內(nèi)聯(lián)等級(inline-level):也就是字體

內(nèi)聯(lián)對象(inline-level object)是塊對象(block-level object)的組成部分,塊對象的所有內(nèi)容都包含在內(nèi)聯(lián)對象中,一個(gè)塊對象由一個(gè)或多個(gè)內(nèi)聯(lián)對象組成,run 是常用的內(nèi)聯(lián)對象,例如:

p = document.add_paragraph('This is paragraph') p.add_run('bold').bold = True p.add_run(' and some ') p.add_run('italic.').italic = True

這個(gè)例子中一個(gè)段落(塊對象)包含三個(gè) run(內(nèi)聯(lián)對象),每一個(gè) run 都設(shè)置有不同屬性

寫word示例:

# coding:utf-8 import sysfrom docx import Document from docx.shared import Inchesdef main():reload(sys)sys.setdefaultencoding('utf-8')# 創(chuàng)建文檔對象document = Document()# 新增樣式(第一個(gè)參數(shù)是樣式名稱,第二個(gè)參數(shù)是樣式類型:1代表段落;2代表字符;3代表表格)style = doc.styles.add_style('style name 1', 2)# 從樣式庫中選取 'Normal' 樣式,并設(shè)置 'Normal' 樣式的字符屬性(font)style = document.styles['Normal']style.font.name = "Microsoft YaHei UI"style.font.size = Pt(50)# 將設(shè)置好字符屬性的樣式運(yùn)用到段落中# p = document.add_paragraph("change font attribution", style = 'Normal')# 從樣式庫中選取 'Heading 2'' 樣式,并設(shè)置段落格式(paragraph format)style = document.styles['Heading 2']style.paragraph_format.left_indent = Pt(20)style.paragraph_format.widow_control = True# 將設(shè)置好段落格式的 style 運(yùn)用到段落中# p = document.add_paragraph('This is Heading, level 1', style = style)# 設(shè)置文檔標(biāo)題,中文要用unicode字符串document.add_heading(u'我的一個(gè)新文檔',0)from docx.shared import RGBColor,Inches,Ptfrom docx.enum.text import WD_ALIGN_PARAGRAPH# 往文檔中添加段落p = document.add_paragraph('This is a paragraph having some ')p.paragraph_format.alignment = WD_ALIGN_PARAGRAPH.CENTER # WD_ALIGN_PARAGRAPH.LEFT,左對齊;WD_ALIGN_PARAGRAPH.RIGHT,右對齊p.paragraph_format.left_indent = Inches(0.5) # 設(shè)置段落從左開始縮進(jìn),使用Inches來衡量p.paragraph_format.right_indent = Pt(20) # 設(shè)置段落從右開始縮進(jìn),使用Pt來衡量p.paragraph_format.first_line_indent = Inches(0.5) # 設(shè)置段落第一行縮進(jìn),可以與上兩個(gè)縮進(jìn)疊加p.paragraph_format.space_after = Pt(5) # 設(shè)置與上一段間隔 Pt(5)p.paragraph_format.space_before = Pt(10) # 設(shè)置與下一段間隔 Pt(10)p.paragraph_format.line_spacing = Pt(18) # 行距p_run = p.add_run('xxx')p_run.font.italic = True # 設(shè)置為斜體p_run.font.size = Pt(12) # 設(shè)置字體大小p_run.font.color.rgb = RGBColor(0, 0, 0) # 設(shè)置字體顏色p_run.font.name = u"宋體" # 設(shè)置字體樣式p_run.font._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體') # 設(shè)置字體樣式p_run.font.underline = False # 不設(shè)置下劃線p_run.font.bold = None # 設(shè)置粗體為繼承上一個(gè)字體的格式# 這一類屬性,每個(gè)有三種狀態(tài):True 為使用屬性;False 為不使用屬性;None 默認(rèn)屬性繼承自上一個(gè)字體# 添加一級標(biāo)題document.add_heading(u'一級標(biāo)題, level = 1',level = 1)document.add_paragraph('Intense quote',style = 'IntenseQuote')# 添加無序列表document.add_paragraph('first item in unordered list',style = 'ListBullet')# 添加有序列表document.add_paragraph('first item in ordered list',style = 'ListNumber')document.add_paragraph('second item in ordered list',style = 'ListNumber')document.add_paragraph('third item in ordered list',style = 'ListNumber')# 添加圖片,并指定寬度document.add_picture('e:/docs/pic.png',width = Inches(1.25))# 添加表格: 1行3列table = document.add_table(rows = 1,cols = 3)# 獲取第一行的單元格列表對象hdr_cells = table.rows[0].cells# 為每一個(gè)單元格賦值,值都要為字符串類型hdr_cells[0].text = 'Name'hdr_cells[1].text = 'Age'hdr_cells[2].text = 'Tel'# 為表格添加一行new_cells = table.add_row().cellsnew_cells[0].text = 'Tom'new_cells[1].text = '19'new_cells[2].text = '12345678'# 添加分頁符document.add_page_break()# 往新的一頁中添加段落p = document.add_paragraph('This is a paragraph in new page.')# 保存文檔document.save('e:/docs/demo1.docx')if __name__ == '__main__':main()

運(yùn)行程序會(huì)得到一個(gè)下面的文檔

三、讀文檔?

對于文件名是中文的讀取時(shí)會(huì)報(bào)錯(cuò)

  • doc.paragraphs??# 段落集合
  • doc.tables? ? ? ? ??# 表格集合
  • doc.sections? ? ? # 節(jié)??集合
  • doc.styles? ? ? ? ? # 樣式集合
  • doc.inline_shapes?# 內(nèi)置圖形?等等...

讀取已有的word文檔示例

# coding:utf-8 import sysfrom docx import Documentdef main():reload(sys)sys.setdefaultencoding('utf-8')# 創(chuàng)建文檔對象,寫自己的 word 路徑document = Document('e:/docs/demo2.docx')# 讀取文檔中所有的段落列表ps = document.paragraphs# 每個(gè)段落有兩個(gè)屬性:style和textps_detail = [(x.text,x.style.name) for x in ps]with open('out.tmp','w+') as fout:fout.write('')# 讀取段落并寫入一個(gè)文件with open('out.tmp','a+') as fout:for p in ps_detail:fout.write(p[0] + '\t' + p[1] + '\n\n')# 讀取文檔中的所有段落的列表tables = document.tables# 遍歷table,并將所有單元格內(nèi)容寫入文件中with open('out.tmp','a+') as fout:for table in tables:for row in table.rows:for cell in row.cells:fout.write(cell.text + '\t')fout.write('\n')if __name__ == '__main__':main()

四、其他事項(xiàng)

1、如果段落中是有超鏈接的,那么段落對象是讀取不出來超鏈接的文本的,需要把超鏈接先轉(zhuǎn)換成普通文本,方法:全選word文檔的所有內(nèi)容,按快捷鍵Ctrl+Shift+F9即可。

2、讀取某些文件時(shí)會(huì)報(bào)錯(cuò),docx.opc.exceptions.PackageNotFoundError: Package not found。原因:docx無法識別doc,需要先手動(dòng)或者使用win32com轉(zhuǎn)換

from win32com import client as wc import docxdef doSaveAas():word = wc.Dispatch('Word.Application')doc = word.Documents.Open(u'E:\old.doc') # 目標(biāo)路徑下的文件doc.SaveAs(u'E:\\new_path.docx', 12, False, "", True, "", False, False, False, False) # 轉(zhuǎn)化后路徑下的文件 doc.Close()word.Quit()doSaveAas()

鏈接https://www.cnblogs.com/jiayongji/p/7290410.html

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

以上是生活随笔為你收集整理的Python 第三方库之docx的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。