python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Excel表格转Word

Python轻松实现将Excel表格完美转换为Word

作者:LSTM97

数据管理与转换在日常工作中扮演着重要角色,本文将教你如何使用 Spire.XLS for Python 和 Spire.Doc for Python 库,轻松将 Excel 数据导出并在 Word 中生成美观的表格,感兴趣的小伙伴可以了解下

数据管理与转换在日常工作中扮演着重要角色。许多情况下,我们需要将 Excel 中的数据导入到 Word 文档中,以便生成报告、制作演示材料或进行文档归档。然而,这个过程不仅涉及到简单的数据搬运,还需要确保格式的完整性,以保持文档的专业性和可读性。本文将教你如何使用 Spire.XLS for Python 和 Spire.Doc for Python 库,轻松将 Excel 数据导出并在 Word 中生成美观的表格,从而提升你的工作效率。

环境准备

首先,确保安装了所需的库。需要使用 Spire.XLS 和 Spire.Doc,Spire.XLS 是一款非常强大的 Excel 文件处理库,支持读取、编辑和生成 Excel 文件(.xlsx 和 .xls 格式);Spire.Doc 是一款功能强大的 Word 文档处理库,允许用户创建、编辑和读取 Word 文档(.doc 和 .docx 格式)。

安装命令:

pip install Spire.XLS
pip install Spire.Doc

代码实现

以下是将 Excel 数据导出为 Word 表格的完整代码示例:

from spire.xls import *
from spire.doc import *

def MergeCells(sheet, table):
    """根据 Excel 工作表中的合并单元格合并 Word 表格中的对应单元格"""
    if sheet.HasMergedCells:
        ranges = sheet.MergedCells
        for i in range(len(ranges)):
            startRow = ranges[i].Row
            startColumn = ranges[i].Column
            rowCount = ranges[i].RowCount
            columnCount = ranges[i].ColumnCount

            if rowCount > 1 and columnCount > 1:
                for j in range(startRow, startRow + rowCount):
                    table.ApplyHorizontalMerge(j - 1, startColumn - 1, startColumn - 1 + columnCount - 1)
                table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount - 1)

            if rowCount > 1 and columnCount == 1:
                table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount - 1)

            if columnCount > 1 and rowCount == 1:
                table.ApplyHorizontalMerge(startRow - 1, startColumn - 1, startColumn - 1 + columnCount - 1)

def CopyStyle(wTextRange, xCell, wCell):
    """将单元格样式从 Excel 复制到 Word"""
    # 复制字体样式
    wTextRange.CharacterFormat.TextColor = Color.FromRgb(xCell.Style.Font.Color.R, xCell.Style.Font.Color.G, xCell.Style.Font.Color.B)
    wTextRange.CharacterFormat.FontSize = float(xCell.Style.Font.Size)
    wTextRange.CharacterFormat.FontName = xCell.Style.Font.FontName
    wTextRange.CharacterFormat.Bold = xCell.Style.Font.IsBold
    wTextRange.CharacterFormat.Italic = xCell.Style.Font.IsItalic

    # 复制背景颜色
    if xCell.Style.FillPattern is not ExcelPatternType.none:
        wCell.CellFormat.BackColor = Color.FromRgb(xCell.Style.Color.R, xCell.Style.Color.G, xCell.Style.Color.B)

    # 复制对齐方式
    wCell.CellFormat.HorizontalAlignment = {
        HorizontalAlignType.Left: HorizontalAlignment.Left,
        HorizontalAlignType.Center: HorizontalAlignment.Center,
        HorizontalAlignType.Right: HorizontalAlignment.Right
    }.get(xCell.HorizontalAlignment)

    wCell.CellFormat.VerticalAlignment = {
        VerticalAlignType.Bottom: VerticalAlignment.Bottom,
        VerticalAlignType.Center: VerticalAlignment.Middle,
        VerticalAlignType.Top: VerticalAlignment.Top
    }.get(xCell.VerticalAlignment)

# 加载 Excel 文件
workbook = Workbook()
workbook.LoadFromFile("Contact list.xlsx")

# 获取第一个工作表
sheet = workbook.Worksheets[0]

# 创建 Word 文档
doc = Document()
section = doc.AddSection()
section.PageSetup.Orientation = PageOrientation.Landscape

# 添加表格
table = section.AddTable(True)
table.ResetCells(sheet.LastRow, sheet.LastColumn)

# 根据 Excel 工作表中的合并单元格合并 Word 表格中的对应单元格
MergeCells(sheet, table)

# 从 Excel 导出数据和单元格样式到 Word 表格
for r in range(1, sheet.LastRow + 1):
    table.Rows[r - 1].Height = float(sheet.Rows[r - 1].RowHeight)

    for c in range(1, sheet.LastColumn + 1):
        xCell = sheet.Range[r, c]
        wCell = table.Rows[r - 1].Cells[c - 1]

        # 复制数据
        textRange = wCell.AddParagraph().AppendText(xCell.NumberText)

        # 复制单元格样式
        CopyStyle(textRange, xCell, wCell)

# 将 Word 文档保存到文件
doc.SaveToFile("Excel转Word表格.docx", FileFormat.Docx)

代码解析

合并单元格 (MergeCells 函数) :为了确保 Excel 中合并的单元格在 Word 中也保持一致,该函数管理合并单元格的逻辑。

复制样式 (CopyStyle 函数) :设计用于将 Excel 单元格的格式(如字体、颜色和对齐方式)精确复制到 Word 表格中。

加载和处理数据 :通过 Spire.XLS 从 Excel 文件中读取数据,然后创建 Word 文档并构建其中的表格。

导出数据 :通过遍历 Excel 的每一行和每一列,将数据导入 Word 表格,并同时应用样式。

总结

使用 Spire.XLS 和 Spire.Doc 库,Python 开发者可以轻松地将 Excel 数据导出到 Word 文档中,并确保格式的完整性。这种转换不仅提高了工作效率,还提升了文档的专业性,适用于各种商业和学术场景。希望本文的代码示例能为你提供帮助,让数据处理工作变得更加顺畅。

到此这篇关于Python轻松实现将Excel表格完美转换为Word的文章就介绍到这了,更多相关Python Excel表格转Word内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文