使用python操作word
阿新 • • 發佈:2017-05-30
data close def pip 行數 pri path http 行數據
有兩種方式:
- 使用win32com
- 使用docx
1.使用win32com擴展包
只對windows平臺有效
代碼:
# coding=utf-8 import win32com from win32com.client import Dispatch, DispatchEx word = Dispatch(‘Word.Application‘) # 打開word應用程序 # word = DispatchEx(‘Word.Application‘) #啟動獨立的進程 word.Visible = 0 # 後臺運行,不顯示 word.DisplayAlerts = 0 # 不警告path = ‘G:/WorkSpace/Python/tmp/test.docx‘ # word文件路徑 doc = word.Documents.Open(FileName=path, Encoding=‘gbk‘) # content = doc.Range(doc.Content.Start, doc.Content.End) # content = doc.Range() print ‘----------------‘ print ‘段落數: ‘, doc.Paragraphs.count # 利用下標遍歷段落 for i in range(len(doc.Paragraphs)): para= doc.Paragraphs[i] print para.Range.text print ‘-------------------------‘ # 直接遍歷段落 for para in doc.paragraphs: print para.Range.text # print para #只能用於文檔內容全英文的情況 doc.Close() # 關閉word文檔 # word.Quit #關閉word程序
2.使用docx擴展包
優點:不依賴操作系統,跨平臺
安裝:
pip install python-docx
參考文檔: https://python-docx.readthedocs.io/en/latest/index.html
代碼:
import docx def read_docx(file_name): doc = docx.Document(file_name) content = ‘\n‘.join([para.text for para in doc.paragraphs]) return content
創建表格
# coding=utf-8 import docx doc = docx.Document() table = doc.add_table(rows=1, cols=3, style=‘Table Grid‘) #創建帶邊框的表格 hdr_cells = table.rows[0].cells # 獲取第0行所有所有單元格 hdr_cells[0].text = ‘Name‘ hdr_cells[1].text = ‘Id‘ hdr_cells[2].text = ‘Desc‘ # 添加三行數據 data_lines = 3 for i in range(data_lines): cells = table.add_row().cells cells[0].text = ‘Name%s‘ % i cells[1].text = ‘Id%s‘ % i cells[2].text = ‘Desc%s‘ % i rows = 2 cols = 4 table = doc.add_table(rows=rows, cols=cols) val = 1 for i in range(rows): cells = table.rows[i].cells for j in range(cols): cells[j].text = str(val * 10) val += 1 doc.save(‘tmp.docx‘)
讀取表格
# coding=utf-8 import docx doc = docx.Document(‘tmp.docx‘) for table in doc.tables: # 遍歷所有表格 print ‘----table------‘ for row in table.rows: # 遍歷表格的所有行 # row_str = ‘\t‘.join([cell.text for cell in row.cells]) # 一行數據 # print row_str for cell in row.cells: print cell.text, ‘\t‘, print
相關樣式參考: https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html
使用python操作word