第十天-自动化办公-word操作

python-docx:操作word

读取word

  1. 安装:

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple python-docx

  1. 使用:

import docx

3.使用document获取对象

注意只支持.docx 格式 不支持doc

from docx import Document

#返回word对象

documnet_obj=Document(word地址)

  1. 段落的读取

#通过循环每个段落的对象,并调用text

for p in documnet_obj.paragraphs:

print(p.text)

5.表格内容的读取

#通过循环获取行列的内容,每个表格字段字符串

for t in documnet_obj.tables:

for row in t.rows:

for cell in row.cells:

print(cell.text)

#根据列读取

for t in documnet_obj.tables:

for col in t.columns:

for cell in col.cells:

print(cell.text)

创建word

  1. 生成标题

document_obj=Document()

#标题样式等级0-9

titleobj=document_obj.add_heading(标题内容,标题样式等级)

#内容追加

titleobj.add_run(字符串)

#保存文档

document_obj.save("xx.docx")

2.保存文档

document_obj=Document()

document_obj.save("xx.docx")

3.添加段落

paraobj=document_obj.add_paragraph("段落内容")

#内容追加

paraobj.add_run("字符串内容")

#可以使用\n来进行换行

4.添加图片

#宽高的定义

from docx.shared import Inches

image_obj=document_obj.add_picture("图片地址",宽,高)

image_obj=document_obj.add_picture("图片地址",width=Inches(5),height=Inches(5))

5.添加表格:add_table

6.分页 add_page_break()

  1. 设置全局样式 document_obj.styles['Noemal']
  • 查看所有样式
  • 设置全局样式
  • 文本样式
  • 图片样式
  • 表格样式

生成pdf

  1. pdf工具包:pdfkit

https://wkhtmltopdf.org/downloads.html中可以下载不同系统的模块

2.html转pdf

3.网址转pdf

4.字符串生成pdf

5.word转html

  1. demo
复制代码
# coding:utf-8

import pdfkit
from pydocx import PyDocX

#html转pdf

#注意需要先按装依赖在:https://wkhtmltopdf.org/downloads.html下载
path_to_wkhtmltopdf = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe'

config = pdfkit.configuration(wkhtmltopdf=path_to_wkhtmltopdf)
#html文件转pdf
#pdfkit.from_file("你好.html","你好1.pdf",configuration=config)

#网址转pdf
#pdfkit.from_url("https://www.imooc.com","慕课网.pdf",configuration=config)

html="""
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<h1>你好</h1>
</body>
</html>
"""
#html字符串转pdf
#pdfkit.from_string(html,"你好.pdf",configuration=config)

#word转pdf 先将word转为html
html_word=PyDocX.to_html("测试.docx")
pdfkit.from_string(html_word,"测试.pdf",configuration=config)
相关推荐
式516几秒前
RAG检索增强生成基础(二)RAG项目实战之Milvus Docker环境配置
运维·docker·容器
Yeats_Liao3 分钟前
容器化部署:基于Docker的推理环境隔离与迁移
运维·docker·容器
xj7573065335 分钟前
Django 面试常见问题
python·面试·django
开开心心就好6 分钟前
内存清理工具点击清理,自动间隔自启
linux·运维·服务器·安全·硬件架构·材料工程·1024程序员节
a努力。6 分钟前
得物Java面试被问:Netty的ByteBuf引用计数和内存释放
java·开发语言·分布式·python·面试·职场和发展
CTO Plus技术服务中7 分钟前
大厂面试笔记和参考答案!浏览器自动化、自动化测试、自动化运维与开发、办公自动化
运维·笔记·面试
winfredzhang9 分钟前
自动化视频制作:深入解析 FFmpeg 图片转视频脚本
ffmpeg·自动化·音视频·命令行·bat·图片2视频
浅安的邂逅13 分钟前
ubuntu 18.04及以上版本 ping命令报错:Name or service not known解决方法
linux·运维·ubuntu·ip设置
重生之绝世牛码15 分钟前
Linux软件安装 —— JDK安装
java·大数据·linux·运维·jdk
晚风吹长发21 分钟前
初步理解Linux中的进程间通信以及管道通信
linux·运维·服务器·c++·进程·通信