国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python操作word常見方法示例【win32com與docx模塊】

2020-02-15 22:26:30
字體:
供稿:網(wǎng)友

本文實例講述了Python操作word常見方法。分享給大家供大家參考,具體如下:

這里介紹兩種方式:

使用win32com 使用docx

1. 使用win32com擴展包

只對windows平臺有效

代碼:

# coding=utf-8import win32comfrom win32com.client import Dispatch, DispatchExword = Dispatch('Word.Application') # 打開word應(yīng)用程序# 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 '段落數(shù): ', doc.Paragraphs.count# 利用下標(biāo)遍歷段落for i in range(len(doc.Paragraphs)):  para = doc.Paragraphs[i]  print para.Range.textprint '-------------------------'# 直接遍歷段落for para in doc.paragraphs:  print para.Range.text  # print para #只能用于文檔內(nèi)容全英文的情況doc.Close() # 關(guān)閉word文檔# word.Quit #關(guān)閉word程序

2. 使用docx擴展包

優(yōu)點:不依賴操作系統(tǒng),跨平臺

安裝:

pip install python-docx

參考文檔: https://python-docx.readthedocs.io/en/latest/index.html

代碼:

import docxdef read_docx(file_name):  doc = docx.Document(file_name)  content = '/n'.join([para.text for para in doc.paragraphs])  return content

創(chuàng)建表格

# coding=utf-8import docxdoc = docx.Document()table = doc.add_table(rows=1, cols=3, style='Table Grid') #創(chuàng)建帶邊框的表格hdr_cells = table.rows[0].cells # 獲取第0行所有所有單元格hdr_cells[0].text = 'Name'hdr_cells[1].text = 'Id'hdr_cells[2].text = 'Desc'# 添加三行數(shù)據(jù)data_lines = 3for 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' % irows = 2cols = 4table = doc.add_table(rows=rows, cols=cols)val = 1for i in range(rows):  cells = table.rows[i].cells  for j in range(cols):    cells[j].text = str(val * 10)    val += 1doc.save('tmp.docx')

讀取表格

# coding=utf-8import docxdoc = 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]) # 一行數(shù)據(jù)    # print row_str    for cell in row.cells:      print cell.text, '/t',    print

相關(guān)樣式參考: https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 新巴尔虎左旗| 兴文县| 平远县| 海丰县| 永善县| 涟源市| 高碑店市| 彭州市| 疏附县| 西吉县| 宜丰县| 弥勒县| 普格县| 洞头县| 建始县| 泾源县| 黎城县| 喜德县| 正宁县| 科尔| 乾安县| 建始县| 枞阳县| 澳门| 陕西省| 峨山| 巴中市| 浑源县| 扬州市| 丹棱县| 通城县| 商水县| 灵璧县| 永兴县| 冀州市| 黄浦区| 九台市| 赫章县| 新建县| 东阳市| 星子县|