一,自動填充數據生成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, Referencewb = Workbook()
ws = wb.activetreeData = [["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
?