python 生成word报告
![report.docx](https://i-blog.csdnimg.cn/blog_migrate/829de527764015b22bb82c11590527c2.png)
import json
from docx import Document
from docx.styles import style, styles
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt, Inches
def getData():
with open("report.json", mode="r", encoding="utf-8") as fp:
data = json.load(fp)
return data["data"]
def writeDoc(data):
doc = Document()
for key, value in data.items():
keyType = key.split("#")[0]
if keyType == "head":
subValue = value["value"]
level = value.get("level", 1)
head = doc.add_heading(subValue, level=level)
head.style.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
head.style.font.size = Inches(0.5)
elif keyType == "paragraph":
doc.add_paragraph(value["value"])
elif keyType == "table":
tableTitle = value["title"]
tableData = value["data"]
paragraph = doc.add_paragraph(tableTitle, style='List Number')
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
paragraph.style.font.size = Pt(14)
rowLen = len(tableData[0])
colLen = len(tableData)
table = doc.add_table(rowLen, colLen)
table.style = "Light List Accent 3"
for index, colValueList in enumerate(tableData):
hdr_cells = table.columns[index].cells
for subindex, colVa in enumerate(colValueList):
hdr_cells[subindex].text = colVa
doc.save("report.docx")
if __name__ == '__main__':
data = getData()
writeDoc(data)