python操作word(生成word文档)

发布于:2025-03-17 ⋅ 阅读:(12) ⋅ 点赞:(0)
from docx.shared import Pt
from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml.ns import qn
import time

temp_val = 15
humid_val = 40

doc = Document()
title = doc.add_paragraph()
title.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
title_run = title.add_run("工作日志")
title_run.font.size = Pt(22)
title_run.font.name = "Times New Roman"
title_run.element.rPr.rFonts.set(qn('w:eastAsia'),"文泉驿正黑")

t1 = doc.add_paragraph("一、环境数据")
t1.style = doc.styles['heading 1']

table = doc.add_table(2,2)
cell = table.cell(0,0)
# cell.text = "dddddddd"
temperature = cell.add_paragraph()
temp_run = temperature.add_run("温度:")

cell = table.cell(0,1)
temperature = cell.add_paragraph()
trun = temperature.add_run(str(temp_val))
trun.font.italic = True
trun.font.size = Pt(24)
temperature.add_run("℃")

cell = table.cell(1,0)
humidity = cell.add_paragraph()
humidity_run = humidity.add_run("湿度:")

cell = table.cell(1,1)
humidity = cell.add_paragraph()
hrun = humidity.add_run(str(humid_val))
hrun.font.italic = True
hrun.font.size = Pt(24)
humidity.add_run("%")

writer = doc.add_paragraph()
writer_run = writer.add_run("name")
writer.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
date = doc.add_paragraph()
current_date = time.strftime("%Y-%m-%d", time.localtime())
date_run = date.add_run(current_date)
date.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT
doc.save(current_date + ".docx")

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'
)

document.add_picture('m.png', width=Inches(5.75))

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('oeasy.docx')


网站公告

今日签到

点亮在社区的每一天
去签到