尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

Python自动化办公:用Spire.Doc轻松搞定带样式的Word报告生成(附完整代码)

Python自动化办公:用Spire.Doc轻松搞定带样式的Word报告生成(附完整代码) Python自动化办公用Spire.Doc轻松搞定带样式的Word报告生成每周重复制作格式统一的业务报告是许多办公人员和开发者的噩梦。手动调整标题样式、页边距、段落间距不仅耗时还容易出错。传统方案如python-docx在样式控制上存在明显短板而Spire.Doc这个低调的Python库却能以极简代码实现专业级文档排版。1. 为什么选择Spire.Doc而非python-docx在自动化文档生成领域python-docx因其简单易用而广为人知。但当我们需要生成带有复杂样式、页眉页脚或公司标准模板的文档时它的局限性就暴露无遗文件体积问题python-docx生成的基础文档体积异常庞大一个简单Hello World文档可能达到36KB样式控制薄弱难以精确控制段落间距、字体变体等细节样式模板支持不足对现有Word模板的复用能力有限Spire.Doc则在这些方面表现优异# 简单对比两种库生成的文件大小 import os from docx import Document from spire.doc import Document as SpireDocument # python-docx生成 docx_doc Document() docx_doc.add_paragraph(测试内容) docx_doc.save(test_docx.docx) print(fpython-docx文件大小: {os.path.getsize(test_docx.docx)/1024:.1f}KB) # Spire.Doc生成 spire_doc SpireDocument() section spire_doc.AddSection() paragraph section.AddParagraph() paragraph.AppendText(测试内容) spire_doc.SaveToFile(test_spire.docx, FileFormat.Docx2019) print(fSpire.Doc文件大小: {os.path.getsize(test_spire.docx)/1024:.1f}KB)典型输出结果python-docx文件大小: 36.2KB Spire.Doc文件大小: 7.8KB2. Spire.Doc核心功能实战2.1 安装与环境配置安装Spire.Doc非常简单pip install Spire.Doc注意Spire.Doc是商业库免费版会有水印和功能限制。对于企业级应用建议购买正式授权。2.2 创建基础文档结构让我们从创建一个标准的业务报告开始from spire.doc import * from spire.doc.common import * # 初始化文档对象 report Document() # 添加章节 section report.AddSection() # 设置页面属性 section.PageSetup.Margins.Top 50 section.PageSetup.Margins.Bottom 50 section.PageSetup.Margins.Left 70 section.PageSetup.Margins.Right 70 section.PageSetup.Orientation PageOrientation.Landscape # 横向页面2.3 高级样式控制Spire.Doc真正的强大之处在于其精细的样式控制能力。下面我们创建一个符合企业标准的标题样式# 创建自定义标题样式 title_style ParagraphStyle(report) title_style.Name CompanyTitle title_style.CharacterFormat.FontName 微软雅黑 title_style.CharacterFormat.FontSize 16 title_style.CharacterFormat.TextColor Color.get_Blue() title_style.ParagraphFormat.HorizontalAlignment HorizontalAlignment.Center title_style.ParagraphFormat.BeforeSpacing 10 title_style.ParagraphFormat.AfterSpacing 15 report.Styles.Add(title_style) # 应用样式 title_paragraph section.AddParagraph() title_paragraph.AppendText(2023年第三季度销售报告) title_paragraph.ApplyStyle(CompanyTitle)对于正文内容我们可以定义多级样式# 正文样式 body_style ParagraphStyle(report) body_style.Name BodyText body_style.CharacterFormat.FontName 宋体 body_style.CharacterFormat.FontSize 12 body_style.ParagraphFormat.LineSpacing 18 body_style.ParagraphFormat.FirstLineIndent 20 report.Styles.Add(body_style) # 小标题样式 subhead_style ParagraphStyle(report) subhead_style.Name Subhead subhead_style.CharacterFormat.FontName 微软雅黑 subhead_style.CharacterFormat.FontSize 14 subhead_style.CharacterFormat.Bold True subhead_style.ParagraphFormat.BeforeSpacing 15 report.Styles.Add(subhead_style)3. 实战自动生成月度业务报告让我们将这些技术整合到一个完整的业务报告生成示例中def generate_monthly_report(data): # 初始化文档 doc Document() section doc.AddSection() # 设置页面 section.PageSetup.Margins.All 50 section.PageSetup.PageSize PageSize.A4 # 添加公司logo header_paragraph section.AddParagraph() header_paragraph.AppendImage(company_logo.png) header_paragraph.Format.HorizontalAlignment HorizontalAlignment.Right # 添加报告标题 title section.AddParagraph() title.AppendText(f{data[month]}月业务报告) title.ApplyStyle(BuiltinStyle.Title) # 添加摘要部分 summary section.AddParagraph() summary.AppendText(执行摘要) summary.ApplyStyle(BuiltinStyle.Heading1) summary_content section.AddParagraph() summary_content.AppendText(data[summary]) summary_content.ApplyStyle(BodyText) # 添加数据表格 table section.AddTable(True) table.ResetCells(len(data[metrics]) 1, 2) # 表头 table.Rows[0].Cells[0].AddParagraph().AppendText(指标) table.Rows[0].Cells[1].AddParagraph().AppendText(数值) # 表格内容 for i, (k, v) in enumerate(data[metrics].items()): table.Rows[i1].Cells[0].AddParagraph().AppendText(k) table.Rows[i1].Cells[1].AddParagraph().AppendText(str(v)) # 设置表格样式 table.TableFormat.Borders.BorderType BorderStyle.Single table.TableFormat.Borders.LineWidth 0.5 # 保存文档 doc.SaveToFile(f{data[month]}_月业务报告.docx, FileFormat.Docx2019)4. 高级功能探索4.1 页眉页脚处理专业文档通常需要统一的页眉页脚# 添加页眉 header section.HeadersFooters.Header header_paragraph header.AddParagraph() header_paragraph.AppendText(机密 - 仅供内部使用) header_paragraph.Format.HorizontalAlignment HorizontalAlignment.Right # 添加页脚 footer section.HeadersFooters.Footer footer_paragraph footer.AddParagraph() footer_paragraph.AppendText(页码: ) footer_paragraph.AppendField(page number, FieldType.FieldPage) footer_paragraph.AppendText( / ) footer_paragraph.AppendField(number of pages, FieldType.FieldNumPages) footer_paragraph.Format.HorizontalAlignment HorizontalAlignment.Center4.2 使用现有模板Spire.Doc可以完美继承现有Word模板的样式# 加载公司模板 template Document() template.LoadFromFile(company_template.docx) # 获取模板中的样式 company_style template.Styles[CompanyHeading] # 在新文档中使用模板样式 new_doc Document() new_section new_doc.AddSection() new_paragraph new_section.AddParagraph() new_paragraph.AppendText(新文档标题) new_paragraph.ApplyStyle(company_style.Name)4.3 批量处理文档结合Python的其他库可以实现文档的批量生成import pandas as pd from spire.doc import * def batch_generate_reports(data_file): # 读取数据 df pd.read_excel(data_file) for _, row in df.iterrows(): doc Document() section doc.AddSection() # 添加客户特定内容 title section.AddParagraph() title.AppendText(f{row[客户名称]}对账单) title.ApplyStyle(BuiltinStyle.Heading1) # 添加表格数据 table section.AddTable(True) table.ResetCells(len(row.items()) 1, 2) # 填充表格... # 保存 doc.SaveToFile(f{row[客户名称]}_对账单.docx, FileFormat.Docx2019) # 使用示例 batch_generate_reports(clients_data.xlsx)在实际项目中Spire.Doc的表现远超python-docx特别是在处理复杂样式和大批量文档时。它的API设计更贴近Word原生功能让开发者能够实现几乎所有的Word排版效果。虽然它的文档相对较少但一旦掌握工作效率能获得质的提升。
返回列表