Python: Convert Excel Data to Word Table with Formatting

2024-11-18 01:07:09 Written by  support iceblue
Rate this item
(0 votes)

Excel is ideal for data calculations, analysis, and organization, while Word shines at creating polished, well-formatted documents and reports. Transferring data from Excel to Word is often necessary for professionals preparing reports or presentations, as it allows for advanced formatting options that enhance readability and create a more professional look. In this guide, you will learn how to convert data in an Excel sheet to a Word table with formatting in Python using Spire.Office for Python.

Install Spire.Office for Python

This scenario requires Spire.Office for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Office

Convert Excel Data to Word Table with Formatting in Python

This process uses two libraries in the Spire.Office for Python package. They’re Spire.XLS for Python and Spire.Doc for Python. The former is used to read data and formatting from an Excel worksheet, and the latter is used to create a Word document and write data, including formatting, into a table. To make this code example easy to understand, we have defined the following two custom methods that handle specific tasks:

  • MergeCells() - Merge the corresponding cells in the Word table based on the merged cells in the Excel sheet.
  • CopyStyle() - Copy various cell styles from the Excel worksheet to the Word table, including font style, background color, and text alignment.

The following steps demonstrate how to convert data from an Excel sheet to a Word table with formatting using Spire.Office for Python.

  • Create an object of the Workbook class and load a sample Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet through the Workbook.Worksheets[index] property.
  • Create a new Word document using the Document class, and add a section to it.
  • Add a table to the Word document using the Section.AddTable() method.
  • Detect the merged cells in the worksheet and merge the corresponding cells in the Word tale using the custom method MergeCells().
  • Iterate through the cells in the worksheet, read the data of the cells through the CellRange.Value property and add the data to Word table cells using the TableCell.AddParagraph().AppendText() method.
  • Copy the cell styles from the Excel worksheet to the Word table using the custom method CopyStyle().
  • Save the Word document to a file using the Document.SaveToFile() method.
  • Python
from spire.xls import *
from spire.doc import *

def MergeCells(sheet, table):
    """Merge cells in the Word table based on merged cells in the Excel sheet."""
    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):
    """Copy cell styling from Excel to Word."""
    # Copy font style
    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

    # Copy background color
    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)

    # Copy horizontal alignment
    if xCell.HorizontalAlignment == HorizontalAlignType.Left:
        wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left
    elif xCell.HorizontalAlignment == HorizontalAlignType.Center:
        wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center
    elif xCell.HorizontalAlignment == HorizontalAlignType.Right:
        wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right

    # Copy vertical alignment
    if xCell.VerticalAlignment == VerticalAlignType.Bottom:
        wCell.CellFormat.VerticalAlignment = VerticalAlignment.Bottom
    elif xCell.VerticalAlignment == VerticalAlignType.Center:
        wCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle
    elif xCell.VerticalAlignment == VerticalAlignType.Top:
        wCell.CellFormat.VerticalAlignment = VerticalAlignment.Top

# Load an Excel file
workbook = Workbook()
workbook.LoadFromFile("Contact list.xlsx")

# Get the first worksheet
sheet = workbook.Worksheets[0]

# Create a Word document
doc = Document()
section = doc.AddSection()
section.PageSetup.Orientation = PageOrientation.Landscape

# Add a table
table = section.AddTable(True)
table.ResetCells(sheet.LastRow, sheet.LastColumn)

# Merge cells
MergeCells(sheet, table)

# Export data and styles from Excel to Word table
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]

        # Add text from Excel to Word table cell
        textRange = wCell.AddParagraph().AppendText(xCell.NumberText)

        # Copy font and cell style
        CopyStyle(textRange, xCell, wCell)

# Save the document to a Word file
doc.SaveToFile("ConvertExcelDataToWordTable.docx", FileFormat.Docx)

Python: Convert Excel Data to Word Table with Formatting

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.