使用 Python 中的格式将 Excel 数据转换为 Word 表格(分步指南)

B站影视 2025-01-26 13:58 3

摘要:要将 Excel 数据转换为 Word 表格,我们将使用两个 Python 库:Spire.XLS for Python用于处理 Excel 文件,Spire.Doc for Python用于处理 Word 文件。

Excel 广泛用于数据管理和计算,而 Word 擅长创建用于通信和演示的文档。将 Excel 数据转换为 Word 表格可以结合这两种工具的优势。

要将 Excel 数据转换为 Word 表格,我们将使用两个 Python 库:Spire.XLS for Python 用于处理 Excel 文件,Spire.Doc for Python 用于处理 Word 文件。

我们可以通过运行以下命令来安装 Spire.XLS for Python 和 Spire.Doc for Python:

pip install spire.xls spire.doc

将 Excel 数据导入 Word 表格并设置格式可以完全控制表格的外观。此方法允许从 Excel 中复制单元格值、字体、颜色、对齐方式和其他样式,从而确保最终的 Word 表格保留原始格式。还可以根据需要应用自定义格式。

我们将该过程分为几个步骤:

第 1 步:加载 Excel 文件。

首先,使用 Workbook 类中的 LoadFromFile 方法加载 Excel 文件。然后,检索包含我们要传输的数据的工作表。

workbook = Workbookworkbook.LoadFromFile("Example.xlsx")sheet = workbook.Worksheets[0]

第 2 步:创建 Word 文档并插入表格。

接下来,使用 document 类创建一个新的 Word 文档。并使用 Table 类的 ResetCells 方法添加一个与 Excel 工作表具有相同行数和列数的表格。

doc = Documentsection = doc.AddSectionsection.PageSetup.Orientation = PageOrientation.Landscapetable = section.AddTable(True)table.ResetCells(sheet.LastRow, sheet.LastColumn)

第 3 步:在 Excel 中处理合并的单元格。

Excel 工作表可能包含合并的单元格,因此适当管理它们非常重要。我们已将这部分 logic 封装在一个方法中:

merge_cells(sheet, table)

以下是 merge_cells 方法的实现:

在这种方法中,我们通过 Worksheet 类的 HasMergedCells 属性检查 Excel 工作表中是否有合并的单元格。如果找到任何合并的单元格,则通过 Table 类的 ApplyHorizongtalMerge 和 ApplyVerticalMerge 方法合并 Word 表中的相应单元格。

def merge_cells(sheet, table): if sheet.HasMergedCells: # Get all merged cell ranges from the Excel worksheet ranges = sheet.MergedCells for merged_range in ranges: # Extract the starting row, column, and the number of rows and columns in the merged range start_row = merged_range.Row start_column = merged_range.Column row_count = merged_range.RowCount column_count = merged_range.ColumnCount # Apply both horizontal and vertical merging if multiple rows and columns are merged if row_count > 1 and column_count > 1: # Apply horizontal merging for each row within the merged range for j in range(start_row, start_row + row_count): table.ApplyHorizontalMerge(j - 1, start_column - 1, start_column - 1 + column_count - 1) # Apply vertical merging across the merged rows table.ApplyVerticalMerge(start_column - 1, start_row - 1, start_row - 1 + row_count - 1) # Apply vertical merging for multi-row merged cells elif row_count > 1: table.ApplyVerticalMerge(start_column - 1, start_row - 1, start_row - 1 + row_count - 1) # Apply horizontal merging for multi-column merged cells elif column_count > 1: table.ApplyHorizontalMerge(start_row - 1, start_column - 1, start_column - 1 + column_count - 1)

第 4 步:使用 Excel 数据填充 Word 表格并将 Excel 样式复制到 Word 表格。

遍历 Excel 工作表的每一行和每一列,将数据和样式从 Excel 单元格复制到 Word 表格。

for r in range(1, sheet.LastRow + 1): # Set row height in the Word table to match the row height in the Excel sheet table.Rows[r - 1].Height = float(sheet.Rows[r - 1].RowHeight) for c in range(1, sheet.LastColumn + 1): # Get the Excel cell at the current row and column x_cell = sheet.Range[r, c] # Get the corresponding Word table cell w_cell = table.Rows[r - 1].Cells[c - 1] # Insert the text from the Excel cell into the Word table cell text_range = w_cell.AddParagraph.AppendText(x_cell.DisplayedText) # copy the style (font, color, alignment, etc.) from the Excel cell to the Word cell copy_style(text_range, x_cell, w_cell)

以下是 copy_style 方法的实现:

在这种方法中,我们将字体属性和样式(背景颜色和对齐方式)从 Excel 单元格复制到 Word 表格单元格。

def copy_style(w_text_range, x_cell, w_cell): # Copy font formatting (text color, font size, name, and style) from Excel cell to Word text range w_text_range.CharacterFormat.TextColor = Color.FromRgb(x_cell.Style.Font.Color.R, x_cell.Style.Font.Color.G, x_cell.Style.Font.Color.B) w_text_range.CharacterFormat.FontSize = float(x_cell.Style.Font.Size) w_text_range.CharacterFormat.FontName = x_cell.Style.Font.FontName w_text_range.CharacterFormat.Bold = x_cell.Style.Font.IsBold w_text_range.CharacterFormat.Italic = x_cell.Style.Font.IsItalic # Copy background color from Excel cell to Word cell if x_cell.Style.FillPattern is not ExcelPatternType.none: w_cell.CellFormat.BackColor = Color.FromRgb(x_cell.Style.Color.R, x_cell.Style.Color.G, x_cell.Style.Color.B) # Copy horizontal alignment from Excel cell to Word paragraph if x_cell.HorizontalAlignment == HorizontalAlignType.Left: w_text_range.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left elif x_cell.HorizontalAlignment == HorizontalAlignType.Center: w_text_range.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center elif x_cell.HorizontalAlignment == HorizontalAlignType.Right: w_text_range.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right # Copy vertical alignment from Excel cell to Word cell if x_cell.VerticalAlignment == VerticalAlignType.Bottom: w_cell.CellFormat.VerticalAlignment = VerticalAlignment.Bottom elif x_cell.VerticalAlignment == VerticalAlignType.Center: w_cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle elif x_cell.VerticalAlignment == VerticalAlignType.Top: w_cell.CellFormat.VerticalAlignment = VerticalAlignment.Top

第 5 步:保存生成的 Word 文档。

最后,使用 Document 类的 SaveToFile 方法保存生成的 Word 文档。

doc.SaveToFile("ExcelToWordTable.docx", FileFormat.Docx2016)

整个代码如下:

from spire.xls import *from spire.doc import *# Function to apply cell merging from Excel sheet to Word table# It checks if the Excel worksheet has merged cells, then merges the corresponding cells in the Word table.def merge_cells(sheet, table): if sheet.HasMergedCells: # Get all merged cell ranges from the Excel worksheet ranges = sheet.MergedCells for merged_range in ranges: # Extract the starting row, column, and the number of rows and columns in the merged range start_row = merged_range.Row start_column = merged_range.Column row_count = merged_range.RowCount column_count = merged_range.ColumnCount # Apply both horizontal and vertical merging if multiple rows and columns are merged if row_count > 1 and column_count > 1: # Apply horizontal merging for each row within the merged range for j in range(start_row, start_row + row_count): table.ApplyHorizontalMerge(j - 1, start_column - 1, start_column - 1 + column_count - 1) # Apply vertical merging across the merged rows table.ApplyVerticalMerge(start_column - 1, start_row - 1, start_row - 1 + row_count - 1) # Apply vertical merging for multi-row merged cells elif row_count > 1: table.ApplyVerticalMerge(start_column - 1, start_row - 1, start_row - 1 + row_count - 1) # Apply horizontal merging for multi-column merged cells elif column_count > 1: table.ApplyHorizontalMerge(start_row - 1, start_column - 1, start_column - 1 + column_count - 1)# Function to copy formatting from Excel cells to Word table cells# It replicates font properties, background color, and alignment (horizontal and vertical) from Excel to Worddef copy_style(w_text_range, x_cell, w_cell): # Copy font formatting (color, size, font name, bold, italic) from Excel cell to Word text range w_text_range.CharacterFormat.TextColor = Color.FromRgb(x_cell.Style.Font.Color.R, x_cell.Style.Font.Color.G, x_cell.Style.Font.Color.B) w_text_range.CharacterFormat.FontSize = float(x_cell.Style.Font.Size) w_text_range.CharacterFormat.FontName = x_cell.Style.Font.FontName w_text_range.CharacterFormat.Bold = x_cell.Style.Font.IsBold w_text_range.CharacterFormat.Italic = x_cell.Style.Font.IsItalic # Copy background color from Excel cell to Word cell if x_cell.Style.FillPattern is not ExcelPatternType.none: w_cell.CellFormat.BackColor = Color.FromRgb(x_cell.Style.Color.R, x_cell.Style.Color.G, x_cell.Style.Color.B) # Copy horizontal alignment from Excel cell to Word paragraph if x_cell.HorizontalAlignment == HorizontalAlignType.Left: w_text_range.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left elif x_cell.HorizontalAlignment == HorizontalAlignType.Center: w_text_range.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center elif x_cell.HorizontalAlignment == HorizontalAlignType.Right: w_text_range.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right # Copy vertical alignment from Excel cell to Word cell if x_cell.VerticalAlignment == VerticalAlignType.Bottom: w_cell.CellFormat.VerticalAlignment = VerticalAlignment.Bottom elif x_cell.VerticalAlignment == VerticalAlignType.Center: w_cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle elif x_cell.VerticalAlignment == VerticalAlignType.Top: w_cell.CellFormat.VerticalAlignment = VerticalAlignment.Top# Load the Excel file into a Workbook objectworkbook = Workbookworkbook.LoadFromFile("Example.xlsx")# Retrieve the first worksheet from the workbooksheet = workbook.Worksheets[0]# Create a new Word documentdoc = Document# Add a section to the document and set the page orientation to landscapesection = doc.AddSectionsection.PageSetup.Orientation = PageOrientation.Landscape# Add a table to the Word document with the same number of rows and columns as in the Excel sheettable = section.AddTable(True)table.ResetCells(sheet.LastRow, sheet.LastColumn)# Apply cell merging in Word table based on Excel merged cellsmerge_cells(sheet, table)# Populate the Word table with data from the Excel sheet and copy the formattingfor r in range(1, sheet.LastRow + 1): # Set row height in the Word table to match the row height in the Excel sheet table.Rows[r - 1].Height = float(sheet.Rows[r - 1].RowHeight) for c in range(1, sheet.LastColumn + 1): # Get the Excel cell at the current row and column x_cell = sheet.Range[r, c] # Get the corresponding Word table cell w_cell = table.Rows[r - 1].Cells[c - 1] # Insert the text from the Excel cell into the Word table cell text_range = w_cell.AddParagraph.AppendText(x_cell.DisplayedText) # Copy the style (font, color, alignment, etc.) from the Excel cell to the Word cell copy_style(text_range, x_cell, w_cell)# Save the generated Word documentdoc.SaveToFile("ExcelToWordTable.docx", FileFormat.Docx2016)doc.Closeworkbook.Dispose

或者,可以将 Excel 数据作为 OLE 对象插入到 Word 中。这种方法将整个 Excel 文件嵌入到 Word 文档中,保持其功能并允许用户双击嵌入的对象以打开和编辑 Excel 数据。

以下是实现此目的的步骤:

首先,使用 Workbook 类中的 LoadFromFile 方法加载 Excel 文件。然后,检索包含我们要传输的数据的工作表。

第 2 步:将工作表转换为图像。

接下来,使用 Worksheet 类的 ToImage 方法将工作表保存到图像中。然后,此图像将用作 Word 文档中 Excel OLE 对象的图标。

image = sheet.ToImage(1, 1, sheet.LastRow, sheet.LastColumn)image.Save("ExcelIcon.png")

第 3 步:创建 Word 文档。

使用 Document 类创建 Word 文档。

doc = Documentsection = doc.AddSection section.PageSetup.Margins.All = 72.0section.PageSetup.Orientation = PageOrientation.Landscape

第 4 步: 加载转换后的图像。

将以前保存的图像加载到 DocPicture 对象中。

picture = DocPicture(doc)picture.LoadImage("ExcelIcon.png")picture.Width = 500.0 picture.Height = 300.0

第 5 步:将 Excel 文件作为 OLE 插入 Word 文档。

向 Word 文档添加一个段落,并将 Excel 文件作为 OLE 对象附加到段落中,并将加载的图像作为图标。

para = section.AddParagraphpara.AppendOleObject("Example.xlsx", picture, OleObjectType.ExcelWorksheet)

第 6 步:保存 Word 文档。

doc.SaveToFile("InsertExcelIntoWordAsOLE.docx", FileFormat.Docx2013)

整个代码如下:

from spire.xls import *from spire.doc import *# Load an Excel file into a Workbook objectworkbook = Workbookworkbook.LoadFromFile("Example.xlsx")# Retrieve the first worksheet from the workbooksheet = workbook.Worksheets[0]# Set the worksheet margins to zero (optional, if not set, the image will have blank margins)sheet.PageSetup.TopMargin = 0.0sheet.PageSetup.BottomMargin = 0.0sheet.PageSetup.LeftMargin = 0.0sheet.PageSetup.RightMargin = 0.0# Convert the worksheet to an image# This image will be used as the icon for the Excel OLE object in the Word documentimage = sheet.ToImage(1, 1, sheet.LastRow, sheet.LastColumn)image.Save("ExcelIcon.png")# Create a Word documentdoc = Document# Add a sectionsection = doc.AddSection # Set page marginssection.PageSetup.Margins.All = 72.0# Set page orientationsection.PageSetup.Orientation = PageOrientation.Landscape # Load the previously saved image into a DocPicture objectpicture = DocPicture(doc)picture.LoadImage("ExcelIcon.png")# Set the width and height of the imagepicture.Width = 500.0 picture.Height = 300.0# Add a paragraph to the sectionpara = section.AddParagraph# Append the Excel file to the paragraph as an OLE object using the loaded image as an iconpara.AppendOleObject("Example.xlsx", picture, OleObjectType.ExcelWorksheet)# Save the Word document with the embedded Excel OLE objectdoc.SaveToFile("InsertExcelIntoWordAsOLE.docx", FileFormat.Docx2013)doc.Closeworkbook.Dispose

来源:自由坦荡的湖泊AI

相关推荐