python如何在word中存储本地图片
作者:乌云飘落 时间:2022-09-13 02:17:53
想要利用Python来操作word文档可以使用docx模块.
安装: pip install python-docx
from docx import Document
from docx.shared import Inches
string = '文字内容'
images = '1.jpg' # 保存在本地的图片
doc = Document() # doc对象
doc.add_paragraph(string) # 添加文字
doc.add_picture(images, width=Inches(2)) # 添加图, 设置宽度
doc.save('word文档.docx') # 保存路径
执行结果: 本地生成了一个Word文档, 打开之后.
但是有时添加图片会产生识别异常:
这是因为图片的格式问题, 对比一下 0.jpg 和 1.jpg的二进制数据, 添加0.jpg会异常, 1.jpg则不会.
解决的方法:
图片格式转换
from docx import Document
from docx.shared import Inches
from PIL import Image
string = '文字内容'
images = '0.jpg' # 保存在本地的图片
doc = Document()
doc.add_paragraph(string) # 添加文字
try:
doc.add_picture(images, width=Inches(2)) # 添加图, 设置宽度
except Exception:
jpg_ima = Image.open(images) # 打开图片
jpg_ima.save('0.jpg') # 保存新的图片
doc.add_picture(images, width=Inches(2)) # 添加图, 设置宽度
doc.save('word文档.docx') # 保存路径
结果就和前面一样了:
来源:https://blog.csdn.net/xuege2017/article/details/84562199
标签:python,word,存储
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
安装python-docx后,无法在pycharm中导入的解决方案
2022-09-08 10:08:13
![](https://img.aspxhome.com/file/2023/3/123463_0s.jpg)
python中使用矢量化替换循环详解
2023-08-27 00:51:01
![](https://img.aspxhome.com/file/2023/1/99161_0s.png)
深入研究WINDOW.EVENT对象
2012-04-26 16:31:58
MySQL操作并使用Python进行连接
2024-01-25 00:54:56
![](https://img.aspxhome.com/file/2023/7/118157_0s.png)
漫谈前端开发中的团队合作
2009-02-05 21:02:00
Python3 读取Word文件方式
2021-03-21 22:36:37
浅谈anaconda python 版本对应关系
2023-12-06 01:02:35
浅析Python自带性能强悍的标准库itertools
2022-04-28 12:45:19
![](https://img.aspxhome.com/file/2023/6/107126_0s.jpg)
python中字典按键或键值排序的实现代码
2023-07-22 00:26:49
一文秒懂pandas中iloc()函数
2023-07-31 18:20:42
![](https://img.aspxhome.com/file/2023/9/76149_0s.png)
Mysql索引性能优化问题解决方案
2024-01-27 12:14:41
![](https://img.aspxhome.com/file/2023/6/110296_0s.png)
彻底解决页面文字编码乱码问题
2022-09-17 02:08:49
mysql执行计划介绍
2024-01-29 10:32:36
![](https://img.aspxhome.com/file/2023/3/112363_0s.jpg)
Golang实现http server提供压缩文件下载功能
2024-05-09 14:56:00
Vue.js实现一个自定义分页组件vue-paginaiton
2024-05-02 16:36:36
![](https://img.aspxhome.com/file/2023/2/130162_0s.jpg)
Vue集成lodop插件实现打印功能
2023-07-02 17:01:20
![](https://img.aspxhome.com/file/2023/2/139892_0s.png)
PHP.vs.JAVA
2023-11-17 20:28:51
![](https://img.aspxhome.com/file/2023/2/85872_0s.jpg)
详解javascript中var与ES6规范中let、const区别与用法
2024-05-09 15:06:17
python jenkins 打包构建代码的示例代码
2022-10-05 02:22:02
mysql启用skip-name-resolve模式时出现Warning的处理办法
2024-01-20 06:44:58