word 自动化处理,又快又好做文档
轻松用python快速生产word文档
1、用python套用word模板,再也不做重复工作
2、用python给word添加图片和表格,神操作
准备:
pip install python-docx
使用顺序:新建文档-》设置默认格式-》建立新的自然段-》添加自然段内容-》设置自然段格式-》保存文档-》关闭
新建文档:document= Document()
设置默认格式:
document.styles['Normal'].font.name = u'微软雅黑' document.styles['Normal'].font.size = Pt(16) # 设置文档的基础字体 document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑') # 设置文档的基础样式
p1 = document.add_paragraph() # 初始化建立第一个自然段
run1 = p1.add_run('关于下达%s产品价格的通知' % (today)) # 这里是第一段的内容 run1.font.name = '微软雅黑' # 设置西文字体 run1._element.rPr.rFonts.set(qn('w:eastAsia'), u'微软雅黑') # 设置中文字体 run1.font.size = Pt(21) # 设置字体大小为21磅 run1.font.bold = True # 设置加粗 p1.space_after = Pt(5) # 段后距离5磅 p1.space_before = Pt(5) # 段前距离5磅
重复以上步骤完成内容
if os.path.exists('D:/autoOffice/%s-价格通知.docx' % i): os.remove('D:/autoOffice/%s-价格通知.docx' % i) document.save('D:/autoOffice/%s-价格通知.docx' % i) # 以“客户名-价格通知”作为文件名保存
需求将文件转换为PDF
准备用pywin32 (pip install pywin32)
from win32com.client import Dispatch, constants, gencache docx_path = 'D:/autoOffice/%s-价格通知.docx'% i pdf_path = 'D:/autoOffice/%s-价格通知.pdf'% i if os.path.exists(docx_path): os.remove(docx_path) document.save(docx_path) gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4) wd = Dispatch("Word.Application") docx = wd.Documents.Open(docx_path, ReadOnly=1) docx.ExportAsFixedFormat(pdf_path, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) wd.Quit(constants.wdDoNotSaveChanges)
import win32com.client # 利用wps完成转化为pdf o = win32com.client.Dispatch("Kwps.Application") o.Visible=False doc = o.Documents.Open(docx_path) doc.ExportAsFixedFormat(pdf_path,17) o.Quit()