在企业日常办公、财务审计或数据报表中,经常需要将Excel中的数据或排版好的表格同步到Word报告里。人工复制粘贴效率低且易出错,本文分享使用Spire.Doc for Python和Spire.XLS for Python组件,通过三种代码方案实现Excel表格到Word文档的集成:数据流动态构建、带格式复制、OLE对象嵌入。我们将对比每种方案的适用场景,并给出完整的Python实现代码。
## 三种方案对比
| 方案 | 原理 | 优势 | 局限 | 适用场景 |
|------|------|------|------|----------|
| 数据流动态构建 | 解析Excel单元格数据,在Word中重建表格 | 格式完全可控,Word文件体积最小 | 无法保留Excel原生公式、图表和底色 | 自动化周报生成、后台数据纯文本导出 |
| 带格式复制 | 提取Excel字体、边框、背景色等样式,渲染至Word | 视觉还原度高,保留排版色彩 | 样式解析较重,大批量处理占用内存大 | 财务资产负债表、需要严格保留颜色的技术看板 |
| OLE对象内嵌 | 将Excel文件作为二进制流内嵌到Word中 | 保持文件原样,双击可唤起Excel编辑 | 文件体积增大,非Windows环境支持有限 | 技术文档附件内嵌、需要交付给业务微调的文档 |
## 环境准备与组件安装
在Python环境中部署以下两个库:
- Spire.Doc for Python:处理Word文档结构
- Spire.XLS for Python:读取Excel数据
这两个组件独立运行,无需安装Microsoft Office。通过pip安装:
- pip install Spire.XLS
- pip install Spire.Doc
复制代码
安装后直接import即可使用。也可安装Spire.Office含更多组件(Spire.PDF、Spire.Presentation等)。
## 方案一:提取Excel数据并在Word中重建表格
当只需要数据,不需保留复杂底色或边框时,使用动态构建。该方法通过Excel组件读取表格数据,在Word中创建同等行列的空表格,然后循环填充数据,对Word文件体积影响最小。
- from spire.doc import Document, AutoFitBehaviorType, FileFormat, DefaultTableStyle
- from spire.xls import Workbook
- # 指定输入与输出文件路径
- excel_file = "/示例文档.xlsx"
- word_file = "/ExcelDataToWord.docx"
- # 创建Workbook实例并加载Excel
- workbook = Workbook()
- workbook.LoadFromFile(excel_file)
- sheet = workbook.Worksheets.get_Item(0)
- allocatedRange = sheet.AllocatedRange
- # 创建Word文档
- doc = Document()
- section = doc.AddSection()
- table = section.AddTable()
- table.ResetCells(allocatedRange.RowCount, allocatedRange.ColumnCount)
- # 遍历填充数据
- for rowIndex in range(allocatedRange.RowCount):
- for colIndex in range(allocatedRange.ColumnCount):
- cell = table.Rows.get_Item(rowIndex).Cells.get_Item(colIndex)
- paragraph = cell.AddParagraph()
- textRange = paragraph.AppendText(allocatedRange.get_Item(rowIndex + 1, colIndex + 1).NumberText)
- textRange.CharacterFormat.FontName = "HarmonyOS Sans SC"
- # 自适应窗口宽度并应用样式
- table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
- table.ApplyStyle(DefaultTableStyle.GridTable1LightAccent6)
- doc.SaveToFile(word_file, FileFormat.Docx2019)
- doc.Dispose()
- workbook.Dispose()
复制代码
**核心要点:**
- sheet.AllocatedRange自动识别含数据的有效单元格范围。
- table.ResetCells()重置Word表格行列数。
- .NumberText属性读取Excel格式化后的最终文本(如千分位、百分比符号)。
- table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)确保表格自适应铺满页面,防止列数过多影响展示。
## 方案二:将Excel表格带格式复制到Word文档
对于财务报表、审计报告等含合并单元格、背景色、字体的场景,需要逐一同步样式。需编写辅助函数处理合并单元格及字体样式复制。
- from spire.xls import Workbook, HorizontalAlignType, ExcelPatternType, VerticalAlignType
- from spire.doc import Document, Color, HorizontalAlignment, VerticalAlignment, PageOrientation, FileFormat
- def MergeCells(worksheet, wordTable):
- if not worksheet.HasMergedCells:
- return
- for cell_range in worksheet.MergedCells:
- start_row, start_col = cell_range.Row, cell_range.Column
- row_count, col_count = cell_range.RowCount, cell_range.ColumnCount
- if col_count > 1:
- for row in range(start_row, start_row + row_count):
- wordTable.ApplyHorizontalMerge(row - 1, start_col - 1, start_col - 1 + col_count - 1)
- if row_count > 1:
- wordTable.ApplyVerticalMerge(start_col - 1, start_row - 1, start_row - 1 + row_count - 1)
- def CopyFormatting(tableTextRange, excelCell, wordCell):
- # 字体样式及颜色
- font = excelCell.Style.Font
- tableTextRange.CharacterFormat.TextColor = Color.FromRgb(font.Color.R, font.Color.G, font.Color.B)
- tableTextRange.CharacterFormat.FontSize = float(font.Size)
- tableTextRange.CharacterFormat.FontName = font.FontName
- tableTextRange.CharacterFormat.Bold = font.IsBold
- tableTextRange.CharacterFormat.Italic = font.IsItalic
- # 背景颜色
- if excelCell.Style.FillPattern != ExcelPatternType.none:
- wordCell.CellFormat.BackColor = Color.FromRgb(excelCell.Style.Color.R, excelCell.Style.Color.G, excelCell.Style.Color.B)
- # 水平对齐方式映射
- hAlignMap = {
- HorizontalAlignType.Left: HorizontalAlignment.Left,
- HorizontalAlignType.Center: HorizontalAlignment.Center,
- HorizontalAlignType.Right: HorizontalAlignment.Right
- }
- if excelCell.HorizontalAlignment in hAlignMap:
- tableTextRange.OwnerParagraph.Format.HorizontalAlignment = hAlignMap[excelCell.HorizontalAlignment]
- # 垂直对齐方式映射
- vAlignMap = {
- VerticalAlignType.Top: VerticalAlignment.Top,
- VerticalAlignType.Center: VerticalAlignment.Middle,
- VerticalAlignType.Bottom: VerticalAlignment.Bottom
- }
- if excelCell.VerticalAlignment in vAlignMap:
- wordCell.CellFormat.VerticalAlignment = vAlignMap[excelCell.VerticalAlignment]
- # 主程序
- excelFileName = "/示例文档.xlsx"
- wordFileName = "/ExcelDataFormatToWord.docx"
- workbook = Workbook()
- workbook.LoadFromFile(excelFileName)
- sheet = workbook.Worksheets.get_Item(0)
- doc = Document()
- section = doc.AddSection()
- section.PageSetup.Orientation = PageOrientation.Landscape # 宽表格推荐横向排版
- table = section.AddTable()
- table.ResetCells(sheet.LastRow, sheet.LastColumn)
- MergeCells(sheet, table)
- for r in range(1, sheet.LastRow + 1):
- tableRow = table.Rows.get_Item(r - 1)
- tableRow.Height = float(sheet.Rows.get_Item(r - 1).RowHeight) # 同步行高
- for c in range(1, sheet.LastColumn + 1):
- eCell = sheet.Range.get_Item(r, c)
- wCell = table.Rows.get_Item(r - 1).Cells.get_Item(c - 1)
- textRange = wCell.AddParagraph().AppendText(eCell.NumberText)
- CopyFormatting(textRange, eCell, wCell)
- doc.SaveToFile(wordFileName, FileFormat.Docx2019)
- doc.Dispose()
- workbook.Dispose()
复制代码
**核心要点:**
- MergeCells函数提取Excel的MergedCells集合,分别调用Word表格的ApplyHorizontalMerge和ApplyVerticalMerge,防止跨组件转换时结构崩坏。
- Color.FromRgb()提取颜色值实现跨文件同步。
- 复制背景色前加ExcelPatternType.none条件,防止无底色单元格被误填为黑色。
- CopyFormatting函数逐一读取Excel单元格的Font和Style属性,赋值给Word字符格式与单元格格式,保持视觉一致。
## 方案三:将Excel表格作为OLE对象内嵌到Word
当需要保留Excel原生编辑能力(如公式、图表)时,可使用OLE对象。先将Excel表格渲染为图片作为封面,再将Excel二进制文件嵌入Word。
- from spire.doc import Document, DocPicture, FileFormat, OleObjectType
- from spire.xls import Workbook
- excelFileName = "示例文档.xlsx"
- wordFileName = "/ExcelOleToWord.docx"
- tempImageName = "SheetImage.png"
- workbook = Workbook()
- workbook.LoadFromFile(excelFileName)
- sheet = workbook.Worksheets.get_Item(0)
- sheet.ToImage(1, 1, sheet.LastRow, sheet.LastColumn).Save(tempImageName)
- doc = Document()
- section = doc.AddSection()
- paragraph = section.AddParagraph()
- pic = DocPicture(doc)
- pic.LoadImage(tempImageName)
- pic.Width = section.PageSetup.PageSize.Width - section.PageSetup.Margins.Left - section.PageSetup.Margins.Right
- ole = paragraph.AppendOleObject(excelFileName, pic, OleObjectType.ExcelWorksheet)
- ole.DisplayAsIcon = False # 显示封面图像而非图标
- doc.SaveToFile(wordFileName, FileFormat.Docx2019)
- workbook.Dispose()
- doc.Dispose()
复制代码
**核心要点:**
- sheet.ToImage()将指定表格区域转换为快照图片。
- 使用PageSize.Width - Margins.Left - Margins.Right自适应缩放,使快照横铺正文。
- paragraph.AppendOleObject()将Excel文件以OLE对象插入,绑定图片作为显示封面。
- 设置ole.DisplayAsIcon为False,确保OLE对象在Word中展示表格图像,且双击可激活Excel编辑。
## 总结
本文介绍了三种用Python将Excel表格嵌入Word文档的方案,每种方案都附有完整代码和核心解析。你可以根据实际需求选择:纯数据迁移用方案一,需保留样式用方案二,需保留编辑能力用方案三。这些代码可直接用于自动化报表生成、财务审计报告等场景,提升文档处理效率。 |