wordoper.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import os, json
  2. #操作word的库
  3. from docx import Document
  4. #设置尺寸的
  5. from docx.shared import Inches
  6. from lib.documentoper import DocumentOper
  7. class WordOper(DocumentOper):
  8. def __init__(self, fileName='', filePath='', fileType=''):
  9. super().__init__(fileName=fileName, filePath=filePath, fileType=fileType)
  10. def setXX(self):
  11. pass
  12. def export(self, exportData):
  13. try:
  14. #要生成的数据
  15. exportObj = json.loads(exportData)
  16. #首先创建一个Word文档对象
  17. document = Document()
  18. #添加标题
  19. document.add_heading('新型冠状病毒肺炎疫情',0)
  20. # 添加段落
  21. p = document.add_paragraph('全国 实时更新_1902_kxy')
  22. p.add_run('粗体').bold = True
  23. p.add_run(' 普通文本 ')
  24. p.add_run('斜体.').italic = True
  25. # 添加1级标题
  26. document.add_heading('一级标题样式', level=1)
  27. # 添加段落,同时设置样式
  28. document.add_paragraph('缩进引用样式', style='Intense Quote')
  29. document.add_paragraph(
  30. '无序列表样式', style='List Bullet'
  31. )
  32. document.add_paragraph(
  33. '有序列表样式', style='List Number'
  34. )
  35. # 添加图片 ,同时设置大小
  36. document.add_picture('upload/img/test_1902_kxy.png', width=Inches(3.25))
  37. # 添加分页符
  38. document.add_page_break()
  39. # 添加表格
  40. table = document.add_table(rows=1, cols=7)
  41. hdr_cells = table.rows[0].cells
  42. hdr_cells[0].text = '序号'
  43. hdr_cells[1].text = '疫情地区'
  44. hdr_cells[2].text = '新增'
  45. hdr_cells[3].text = '现有'
  46. hdr_cells[4].text = '累计'
  47. hdr_cells[5].text = '治愈'
  48. hdr_cells[6].text = '死亡'
  49. for index, item in enumerate(exportObj['list']):
  50. row_cells = table.add_row().cells
  51. row_cells[0].text = str(index+1)
  52. row_cells[1].text = item['area']
  53. row_cells[2].text = item['confirmedRelative']
  54. row_cells[3].text = item['curConfirm']
  55. row_cells[4].text = item['confirmed']
  56. row_cells[5].text = item['crued']
  57. row_cells[6].text = item['died']
  58. # 文档保存
  59. document.save(super().setFullPath())
  60. return 'success'
  61. except Exception as ex:
  62. print(ex)
  63. return 'failure'