python如何写word_利用python向word中写入内容

##作业

##制作一个自动生成请假条word文档的程序

##通过命令行提示用户输入姓名、请假原因

##自动生成代标题、正文内容的请假条

##日期自动填写今天日期

from docx import Document

import time

from docx.shared import Cm,Pt

from docx.enum.text import WD_PARAGRAPH_ALIGNMENT

year=time.localtime(time.time()).tm_year

month=time.localtime(time.time()).tm_mon

day=time.localtime(time.time()).tm_mday

#确定年月日

doc=Document()

name=input('请输入您的姓名:')

reason=input('请输入您请假的原因:')

#输入姓名盒轻雅原因

paragraph0=doc.add_paragraph('请假条')

paragraph0.alignment=WD_PARAGRAPH_ALIGNMENT.CENTER

#设置第一段标题居中

paragraph1=doc.add_paragraph('尊敬的老师您好:')

#对老师的敬语

paragraph2=doc.add_paragraph(f'我是{name},现在因为{reason}要去医院看病特向您请假,请您批准。')

paragraph2.paragraph_format.first_line_indent=Cm(0.75)

#第3段首行缩进0.75cm

paragraph3=doc.add_paragraph(f'{name}')

paragraph3.alignment=WD_PARAGRAPH_ALIGNMENT.RIGHT

paragraph4=doc.add_paragraph(f'{year}年{month}月{day}日')

paragraph4.alignment=WD_PARAGRAPH_ALIGNMENT.RIGHT

#第3,4段落款姓名和时间,设置右对齐

doc.save('请假条.docx')

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Python的docx和openpyxl库来实现从Word文档读取内容写入Excel文件。 首先,需要安装docx和openpyxl库。可以使用以下命令进行安装: ``` pip install python-docx openpyxl ``` 接下来,可以使用以下代码读取Word文档内容: ```python import docx # 打开Word文档 doc = docx.Document('example.docx') # 遍历文档的段落 for para in doc.paragraphs: # 打印每个段落的内容 print(para.text) # 遍历文档的表格 for table in doc.tables: # 遍历表格的行 for row in table.rows: # 遍历行的单元格 for cell in row.cells: # 打印每个单元格的内容 print(cell.text) ``` 接下来,可以使用以下代码将读取的内容写入Excel文件: ```python import docx from openpyxl import Workbook # 打开Word文档 doc = docx.Document('example.docx') # 创建Excel文件 wb = Workbook() ws = wb.active # 遍历文档的段落 for para in doc.paragraphs: # 将每个段落的内容写入Excel文件 ws.append([para.text]) # 遍历文档的表格 for table in doc.tables: # 遍历表格的行 for row in table.rows: # 创建一个空列表用于存储行的单元格内容 row_data = [] # 遍历行的单元格 for cell in row.cells: # 将每个单元格的内容添加到列表 row_data.append(cell.text) # 将列表内容写入Excel文件 ws.append(row_data) # 保存Excel文件 wb.save('example.xlsx') ``` 以上代码将文档的每个段落作为一行写入Excel文件,将表格的每个单元格作为一列写入Excel文件。可以根据需要进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值