python对word内容,python word文档

发布时间:2022-11-18

本文目录一览:

  1. python中如何将word表格内的内容进行替换
  2. python输出word内容
  3. word文字替换批处理之python
  4. python读取word文档内容

python中如何将word表格内的内容进行替换

在使用word中的一个自然段,就是一个paragraph,最简单的方式如下命令获得全部的段落,这是一个可迭代的类型,类似于数组方式。就可以直接获得文章中的第一段第一段的全部文字内容,如果我们连贯起来代码如下获得run其实也是非常简单的如下命令python-docx这个包,不仅可以读出paragraph的内容,还可以往里面写。可以使用add_paragraph()方法来添加内容。如下命令代码每一个属性都可以查看它的类型,这个类型一般在docx中是个枚举类型的常量,放在docx.enum.text这个头文件中。

python输出word内容

程序导出word文档的方法 将web/html内容导出为world文档,再java中有很多解决方案,比如使用Jacob、Apache POI、Java2Word、iText等各种方式,以及使用freemarker这样的模板引擎这样的方式。php中也有一些相应的方法,但在python中将web/html内容生成world文档的方法是很少的。其中最不好解决的就是如何将使用js代码异步获取填充的数据,图片导出到word文档中。

1. unoconv

功能:

  1. 支持将本地html文档转换为docx格式的文档,所以需要先将网页中的html文件保存到本地,再调用unoconv进行转换。转换效果也不错,使用方法非常简单。 安装
sudo apt-get install unoconv

使用

unoconv -f pdf *.odt
unoconv -f doc *.odt
unoconv -f html *.odt

缺点:

  1. 只能对静态html进行转换,对于页面中有使用ajax异步获取数据的地方也不能转换(主要是要保证从web页面保存下来的html文件中有数据)。
  2. 只能对html进行转换,如果页面中有使用echarts,highcharts等js代码生成的图片,是无法将这些图片转换到word文档中。
  3. 生成的word文档内容格式不容易控制。

2. python-docx

功能:

  1. python-docx是一个可以读写word文档的python库。 使用方法:
  2. 获取网页中的数据,使用python手动排版添加到word文档中。
from docx import Document
from docx.shared import Inches
document = Document()
document.add_heading('Document Title', 0)
p = document.add_paragraph('A plain paragraph having some ')
p.add_run('bold').bold = True
p.add_run(' and some ')
p.add_run('italic.').italic = True
document.add_heading('Heading, 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_picture('monty-truth.png', width=Inches(1.25))
table = document.add_table(rows=1, cols=3)
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Qty'
hdr_cells[1].text = 'Id'
hdr_cells[2].text = 'Desc'
for item in recordset:
    row_cells = table.add_row().cells
    row_cells[0].text = str(item.qty)
    row_cells[1].text = str(item.id)
    row_cells[2].text = item.desc
document.add_page_break()
document.save('demo.docx')
from docx import Document
from docx.shared import Inches
document = Document()
for row in range(9):
    t = document.add_table(rows=1,cols=1,style = 'Table Grid')
    t.autofit = False #很重要!
    w = float(row) / 2.0
    t.columns[0].width = Inches(w)
document.save('table-step.docx')

缺点:

  1. 功能非常弱。有很多限制比如不支持模板等,只能生成简单格式的word文档。

程序导出PDF文档方法

1. pdfkit

功能:

  1. wkhtmltopdf主要用于HTML生成PDF。
  2. pdfkit是基于wkhtmltopdf的python封装,支持URL,本地文件,文本内容到PDF的转换,其最终还是调用wkhtmltopdf命令。是目前接触到的python生成pdf效果较好的。 优点:
  3. wkhtmltopdf:利用webkit内核将HTML转为PDF
  4. webkit是一个高效、开源的浏览器内核,包括Chrome和Safari在内的浏览器都使用了这个内核。Chrome打印当前网页的功能,其中有一个选项就是直接“保存为 PDF”。
  5. wkhtmltopdf使用webkit内核的PDF渲染引擎来将HTML页面转换为PDF。高保真,转换质量很好,且使用非常简单。 使用方法: 安装
pip install pdfkit

使用

import pdfkit
pdfkit.from_url('', 'out.pdf')
pdfkit.from_file('test.html', 'out.pdf')
pdfkit.from_string('Hello!', 'out.pdf')

缺点:

  1. 对使用echarts,highcharts这样的js代码生成的图标无法转换为pdf(因为它的功能主要是将html转换为pdf,而不是将js转换为pdf)。对于纯静态页面的转换效果还是不错的。

2. 其他

其他生成pdf的插件还有:weasyprint,reportlab,PyPDF2等,经简单试验都不如pdfkit效果好,且有些用法复杂。

word文字替换批处理之python

媳妇有无数word文档要替换,百度后发现没有现成的方法。 google后没有太合适的。抄抄写写弄个python脚本换目录下所有word内容,共勉之。

import os
from docx import Document
# 放了一些docx 文件
files_dict ={
    "/home/test/a/医疗器械临床试验第一版-设计/": "/home/test/a/医疗器械临床试验第一版-设计/",
    "/home/test/a/医疗器械临床试验第一版-管理制度/": "/home/test/a/医疗器械临床试验第一版-管理制度/",
    "/home/test/a/医疗器械临床试验第一版-SOP/": "/home/test/a/医疗器械临床试验第一版-SOP/",
    "/home/test/a/目录/": "/home/test/a/目录/"
}
replace_dict = {
    "XXGNK":"XZDXGWK",
    "心血管专业": "心脏大血管外科",
    "心血管":"心脏大血管外科",
}
def check_and_change(document, replace_dict):
    """
    遍历word中的所有 paragraphs,在每一段中发现含有key 的内容,就替换为 value 。
    (key 和 value 都是replace_dict中的键值对。)
    """
    for para in document.paragraphs:
        for i in range(len(para.runs)):
            for key, value in replace_dict.items():
                if key in para.runs[i].text:
                    print(key+"--"+value)
                    para.runs[i].text = para.runs[i].text.replace(key, value)
    for table in document.tables:
        for row in table.rows:
            for cell in row.cells:
                for para in cell.paragraphs:
                    for i in range(len(para.runs)):
                        for key, value in replace_dict.items():
                            if key in para.runs[i].text:
                                print(key+"--"+value)
                                para.runs[i].text = para.runs[i].text.replace(key, value)
    return document
def main():
    for old_file_path, new_file_path in files_dict.items():
        for name in os.listdir(old_file_path):
            print(name)
            old_file = old_file_path + name
            new_file = new_file_path + name
            if old_file.split(".")[1] == 'docx':
                document = Document(old_file)
                document = check_and_change(document, replace_dict)
                document.save(new_file)
            print("^"*30)
if __name__ == '__main__':
    main()

python读取word文档内容

import fnmatch, os, sys, win32com.client
readpath=r'D:\123'
wordapp = win32com.client.gencache.EnsureDispatch("Word.Application")
try:
    for path, dirs, files in os.walk(readpath):
        for filename in files:
            if not fnmatch.fnmatch(filename, '*.docx'):
                continue
            doc = os.path.abspath(os.path.join(path,filename))
            print 'processing %s...' % doc
            wordapp.Documents.Open(doc)
            docastext = doc[:-4] + 'txt'
            wordapp.ActiveDocument.SaveAs(docastext,FileFormat=win32com.client.constants.wdFormatText)
            wordapp.ActiveDocument.Close()
finally:
    wordapp.Quit()
    print 'end'
f=open(r'd:\123\test.txt','r')
for line in f.readlines():
    print line.decode('gbk')
f.close()