啊峰哥

打开和写入word文档

一. 使用win32读取word内容

# -*- coding: utf-8 -*-

from win32com import client as wc

def readDocx2():
    word = wc.Dispatch('Word.Application')                                        # 使用WORD应用程序
    word.Visible = 0                                                              # 不打开界面

    my_worddoc = word.Documents.Open(u'新建文本文档.docx')                          # 打开word文档
    paragraphs = my_worddoc.Paragraphs.Count                                      # 计算段落数
    for i in range(paragraphs):
        my_pr = my_worddoc.Paragraphs[i].Range                                    # 读取每段并打印
        print my_pr.text                                                      
    my_worddoc.Close()
readDocx2()

 

二.使用模块docx读取word内容

# -*- coding: utf-8 -*-import docx

def read_docx(filename):                             #filename为文件地址
    doc = docx.Document(filename)                    #打开docx文档
    fulltext = []                                    #创建空列表
    for para in doc.paragraphs:                      #遍历所有段落的文字内容
        fulltext.append(para.text)                   #将所有文字内容添加到列表fulltext中
    return '\n'.join(fulltext)                       #进行分段,返回原文

a = read_docx(u'新建文本文档.docx') 
print a                                              #打印出来

 三.写入word文档

# -*- coding: utf-8 -*-
from
docx import Document from docx.shared import Inches document = Document() document.add_heading('This is a Title', 0) #添加题目 p = document.add_paragraph('This is a paragraph') #添加段落内容 p.add_run('bold').bold = True #设置粗体和格式 p.add_run(' and some ') p.add_run('italic.').italic = True document.add_heading('This is a heading with level1', level=1) #级别为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' #添加段落内容并设置格式,带有序号 )
#设置文本内容
text = ''' aaaa
bbb
ccc
ddd'''
document.add_paragraph(text) #添加大量文本内容... document.add_page_break() document.save('demo.docx') #保存路径...

 

posted on 2017-09-23 17:08  啊峰哥  阅读(984)  评论(0编辑  收藏  举报

导航