docx模塊:對word文檔的處理
讀取docx文件
from docx import Document # word處理模塊
path = r"C:\Users\30797\Desktop\python\docx.docx"
document = Document(path) # 讀取docx文件
處理段落(paragraphs)
1、遍歷輸出段落
paragraphs = document.paragraphs
for paragraph in paragraphs: # 遍歷所有段落
print(paragraph.text)
2、讀取第二段樣式
runs = paragraphs[1].runs # 讀取第二段所有樣式
for run in runs: # 遍歷輸出所有樣式
print(run.text)
3、將 "Jan 1 2020" 改爲 "Jan 1 2021" 並且不改變樣式。由上可知,"Jan 1 2020" 的樣式爲 "runs[3]" ,所以代碼如下:
runs[3].text = "Jan 1 2021" # 更改日期內容且不改變樣式
document.save(path) # 保存更改
注:"paragraphs[1].text = "Date:Jan 1 2021" 也能更改內容,但不同的是它將會改變樣式
4、增加一段
document.add_paragraph("End") # 增加一段
document.save(path) # 保存更改
處理表格(tables)
1、遍歷輸出表格
tables = document.tables
for table in tables: # 遍歷所有表格
for row in range(len(table.rows)): # 遍歷行
for col in range(len(table.columns)): # 遍歷列
print(table.cell(row, col).text, end=' ') # 輸出每格的內容
print()
2、將 "2020" 改爲 "2021" 並且不改變樣式
tables[0].cell(1, 2).paragraphs[0].runs[0].text = "2021" # 2020的位置爲第1個表格,第2行第3列,段落1,樣式1
document.save(path) # 保存更改
win32com模塊:直接操作office軟件
from win32com.client import Dispatch, constants
w = Dispatch('Word.Application')
# 或者使用下面的方法,使用啓動獨立的進程:
# w = DispatchEx('Word.Application')
# 後臺運行,不顯示,不警告
w.Visible = 0
w.DisplayAlerts = 0
# 打開新的文件
doc = w.Documents.Open( FileName = filenamein )
# worddoc = w.Documents.Add() # 創建新的文檔
# 插入文字
myRange = doc.Range(0,0)
myRange.InsertBefore('Hello from Python!')
# 使用樣式
wordSel = myRange.Select()
wordSel.Style = constants.wdStyleHeading1
# 正文文字替換
w.Selection.Find.ClearFormatting()
w.Selection.Find.Replacement.ClearFormatting()
w.Selection.Find.Execute(OldStr, False, False, False, False, False, True, 1, True, NewStr, 2)
# 頁眉文字替換
w.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting()
w.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting()
w.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute(OldStr, False, False, False, False, False, True, 1, False, NewStr, 2)
# 表格操作
doc.Tables[0].Rows[0].Cells[0].Range.Text ='123123'
worddoc.Tables[0].Rows.Add() # 增加一行
# 轉換爲html
wc = win32com.client.constants
w.ActiveDocument.WebOptions.RelyOnCSS = 1
w.ActiveDocument.WebOptions.OptimizeForBrowser = 1
w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4
w.ActiveDocument.WebOptions.OrganizeInFolder = 0
w.ActiveDocument.WebOptions.UseLongFileNames = 1
w.ActiveDocument.WebOptions.RelyOnVML = 0
w.ActiveDocument.WebOptions.AllowPNG = 1
w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat = wc.wdFormatHTML )
# 打印
doc.PrintOut()
# 關閉
# doc.Close()
w.Documents.Close(wc.wdDoNotSaveChanges)
w.Quit()
openpyxl模塊:對excel文檔的處理
from openpyxl import load_workbook, comments
# 加載、讀取excel溥
workbook = load_workbook(path)
# 讀取表格
sheet = workbook['Sheetname']
# 表最大行、列數
row = sheet.max_row
column = sheet.max_column
# 讀取x行、y列單元格的值
value = sheet.cell(x, y).value
# 爲x行、y列單元格添加註釋
sheet.cell(x, y).comment = comments.Comment('Content', 'Auther')
# 保存工作溥
workbook.save(path)