python - 如何在 .Doc 文件上写入字符串
问题描述
如何使用python将字符串写入.Doc文件?
<class 'str'>
我需要类似的.to_csv(),to_json()
方法来创建 doc 文件。
解决方案
使用 python-docx 模块
来自https://python-docx.readthedocs.io/en/latest/的示例代码
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='Intense Quote')
document.add_paragraph(
'first item in unordered list', style='List Bullet'
)
document.add_paragraph(
'first item in ordered list', style='List Number'
)
#don'thave picture on my pc
#document.add_picture('monty-truth.png', width=Inches(1.25))
records = (
(3, '101', 'Spam'),
(7, '422', 'Eggs'),
(4, '631', 'Spam, spam, eggs, and spam')
)
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 qty, id, desc in records:
row_cells = table.add_row().cells
row_cells[0].text = str(qty)
row_cells[1].text = id
row_cells[2].text = desc
document.add_page_break()
document.save('data/demo.docx')
推荐阅读
- java - 如何在单个请求中发送多个 JSON(Jmeter)
- kubernetes - 等待 http-01 质询传播:未能执行自我超时
- javascript - 在 JavaScript 中通过构造函数定义方法
- java - 在 Windows 10 中,Java swing 组件在屏幕上的位置在 x 轴上偏移 10 个像素
- android - 字体在 android 模拟器中没有变化,但在预览中可以正常工作
- ios - 使用 Firebase/Crashlytics 更改 Fabric 和 Crashlytics pod 以上传缺少的必需 dSYM
- python - 如何根据偏移量和方向在 Python 中对列表进行排序?
- python - xarray 坐标相关计算
- jquery - 在反应中使用 jquery 的第三方库的动画
- python - 在 requirements.txt 中不包含我自己的包的最佳方法是什么?