Python脚本自动填充数据和生成文档轻松办公

一,自动填充数据生成word文档

代码:


from docx import Document

# 创建一个新的Word文档对象
doc = Document()

# 添加标题
doc.add_heading('自动填充数据和生成文档', level=1)

# 添加段落
doc.add_paragraph('这是一个使用Python脚本自动填充数据并生成文档的示例。')

# 添加表格
table = doc.add_table(rows=3, cols=2)
table.style = 'Table Grid'

# 填充表格数据
table.cell(0, 0).text = '姓名'
table.cell(0, 1).text = '年龄'
table.cell(1, 0).text = '张三'
table.cell(1, 1).text = '25'
table.cell(2, 0).text = '李四'
table.cell(2, 1).text = '30'

# 保存文档
doc.save('Python自动填充数据和生成文档.docx')

执行结果:

 

 

二、Excel办公自动化(创建简单的电子表格和条形图)

代码:


from openpyxl import Workbook
from openpyxl.styles import Font
from openpyxl.chart import BarChart, Reference

wb = Workbook()
ws = wb.active

treeData = [["Type", "Leaf Color", "Height"], ["Maple", "Red", 549], ["Oak", "Green", 783], ["Pine", "Green", 1204]]
print(treeData)
# 将列表数据输入到工作表 Worksheet.append()
for row in treeData:
    ws.append(row)
# 标题行中的所有单元格设置为粗体。styles.Font
ft = Font(bold=True)
for row in ws["A1:C1"]:
    for cell in row:
        cell.font = ft

# 制作图表
chart=BarChart()
chart.type = "col"
# 题目
chart.title = "Tree Height"
# Y轴
chart.y_axis.title = 'Height (cm)'
# X轴
chart.x_axis.title = 'Tree Type'
chart.legend = None

# 需要添加对数据所在位置的引用,并将其传递给图表对象
data = Reference(ws, min_col=3, min_row=2, max_row=4, max_col=3)
categories = Reference(ws, min_col=1, min_row=2, max_row=4, max_col=1)

chart.add_data(data)
chart.set_categories(categories)

# 保存
ws.add_chart(chart, "E1")
wb.save("file7.xlsx")

结果:

 

三、PDF办公自动化(pdf转为word)

首先导入了pdf2docx库中的Converter类。然后,指定输入的PDF文件路径和输出的Word文件路径。接着,创建了一个转换器对象cv,并调用其convert方法将PDF转换为Word。最后,关闭转换器对象。

pip install pdf2docx

事先准备好一个pdf文件

代码:


from pdf2docx import Converter

# 转换前pdf路径
pdf_file = '金钼股份2020年第三季度报告正文.pdf'
# 转换后Word路径
docx_file = '金钼股份2020年第三季度报告正文.docx'

# 创建一个转换器对象
cv = Converter(pdf_file)

# 将PDF转换为Word
cv.convert(docx_file, start=0, end=None)

# 关闭转换器
cv.close()

执行结果:

[INFO] Start to convert 金钼股份2020年第三季度报告正文.pdf
[INFO] [1/4] Opening document...
[INFO] [2/4] Analyzing document...
[INFO] [3/4] Parsing pages...
[INFO] (1/8) Page 1
[INFO] (2/8) Page 2
[INFO] (3/8) Page 3
[INFO] (4/8) Page 4
[INFO] (5/8) Page 5
[INFO] (6/8) Page 6
[INFO] (7/8) Page 7
[INFO] (8/8) Page 8
[INFO] [4/4] Creating pages...
[INFO] (1/8) Page 1
[INFO] (2/8) Page 2
[INFO] (3/8) Page 3
[INFO] (4/8) Page 4
[INFO] (5/8) Page 5
[INFO] (6/8) Page 6
[INFO] (7/8) Page 7
[INFO] (8/8) Page 8
[INFO] Terminated in 7.32s.

进程已结束,退出代码为 0

 

  • 13
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图灵学者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值