Python办公自动化套件 | 开发日志

Python办公自动化套件

March 19, 2022

类别: Python 标签: word python-docx excel openpyxl

操作 Word 文档

安装依赖库 python-docx

  1. pip install python-docx

示例

  1. from docx import Document
  2. from docx.shared import Inches
  3. document = Document()
  4. document.add_heading('Document Title', 0)
  5. p = document.add_paragraph('A plain paragraph having some ')
  6. p.add_run('bold').bold = True
  7. p.add_run(' and some ')
  8. p.add_run('italic.').italic = True
  9. document.add_heading('Heading, level 1', level=1)
  10. document.add_paragraph('Intense quote', style='Intense Quote')
  11. document.add_paragraph(
  12. 'first item in unordered list', style='List Bullet'
  13. )
  14. document.add_paragraph(
  15. 'first item in ordered list', style='List Number'
  16. )
  17. document.add_picture('monty-truth.png', width=Inches(1.25))
  18. records = (
  19. (3, '101', 'Spam'),
  20. (7, '422', 'Eggs'),
  21. (4, '631', 'Spam, spam, eggs, and spam')
  22. )
  23. table = document.add_table(rows=1, cols=3)
  24. hdr_cells = table.rows[0].cells
  25. hdr_cells[0].text = 'Qty'
  26. hdr_cells[1].text = 'Id'
  27. hdr_cells[2].text = 'Desc'
  28. for qty, id, desc in records:
  29. row_cells = table.add_row().cells
  30. row_cells[0].text = str(qty)
  31. row_cells[1].text = id
  32. row_cells[2].text = desc
  33. document.add_page_break()
  34. document.save('demo.docx')

Python办公自动化套件 _ 开发日志 - 图1

操作 Excel 文档

安装依赖库 openpyxl

  1. pip install openpyxl

示例

  1. from openpyxl import Workbook
  2. wb = Workbook()
  3. # grab the active worksheet
  4. ws = wb.active
  5. # Data can be assigned directly to cells
  6. ws['A1'] = 42
  7. # Rows can also be appended
  8. ws.append([1, 2, 3])
  9. # Python types will automatically be converted
  10. import datetime
  11. ws['A2'] = datetime.datetime.now()
  12. # Save the file
  13. wb.save("sample.xlsx")

参考资料