跳至页脚内容
使用 IRONXL FOR PYTHON

如何使用 Python 将 Excel 文件中的单元格合并

In the world of spreadsheet manipulation, Excel stands as a foundational tool, offering a multitude of functionalities catering to various needs in finance, engineering, statistics, and beyond. Among its many features, the ability to merge specific cells in Excel is one often employed to enhance data presentation and visualization. In the dynamic landscape of data management, organizing and consolidating data efficiently is paramount. Excel, with its versatile features, serves as a go-to tool for many professionals. However, when it comes to merging or unmerging cells in Excel programmatically, Python emerges as a powerful ally. In this article, we'll explore how Python, coupled with a library like IronXL, simplifies the process of merging cells in a new Excel file, enabling users to streamline their data organization workflows.

How to Merge Cells in an Excel File Using Python

  1. Install IronXL.
  2. Load existing Workbook.
  3. Select Excel Worksheet.
  4. Use the Merge function to merge specific cells.
  5. Use the Unmerge function to unmerge cells in Excel.

Why Use IronXL?

IronXL is a powerful Python library developed and maintained by Iron Software. Its primary purpose is to provide an intuitive and efficient way to work with Excel files (and other spreadsheet formats) in Python applications and websites. Here are some key features of IronXL:

  1. IronXL allows you to read data from existing Excel files (XLSX, XLS, XLSM, XLTX, CSV, and TSV). You can also generate new Excel files and edit existing ones programmatically.
  2. IronXL works seamlessly across different platforms, including Windows, macOS, Linux, Docker, Azure, and AWS. Whether you’re developing on your local machine or deploying to the cloud, IronXL has you covered.
  3. The library provides an easy-to-use API for working with Excel spreadsheets. You can load workbooks, select worksheets, read cell values, apply styles, unmerge cells, and perform various operations without a complex setup.
  4. IronXL allows you to style cells by setting font properties, background patterns, borders, and alignment. You can format cell values as text, numbers, dates, currency, percentages, and more.
  5. You can work with Excel formulas, and they are recalculated every time a sheet is edited. Perform calculations on ranges of cells, such as finding the sum, minimum, or maximum value.

Using IronXL to Merge Cells in Excel File

Before we begin, make sure you have IronXL installed. You can install it using pip:

pip install ironxl
pip install ironxl
SHELL

This will install IronXL in our Project.

Load Excel Workbook

The very first step is to load the Excel workbook into memory. We will load the following Excel file and utilize it throughout this tutorial.

How to Merge Cells in an Excel File Using Python: Figure 1 - Excel File Input

The following code will load the existing workbook in our project.

from ironxl import *  # Import entire module from ironxl for Excel operations

# Set license key for IronXL (Replace the license key with an actual valid key)
License.LicenseKey = "IRONSUITE.XYZ.ABC.COM.15796-DEPLOYMENT.TRIAL-5X73V4.TRIAL.EXPIRES.27.MAY.2024"

# Load existing workbook
workbook = WorkBook.Load("test_excel.xlsx")
from ironxl import *  # Import entire module from ironxl for Excel operations

# Set license key for IronXL (Replace the license key with an actual valid key)
License.LicenseKey = "IRONSUITE.XYZ.ABC.COM.15796-DEPLOYMENT.TRIAL-5X73V4.TRIAL.EXPIRES.27.MAY.2024"

# Load existing workbook
workbook = WorkBook.Load("test_excel.xlsx")
PYTHON

The above Python code demonstrates the usage of IronXL, a library for working with Excel files. After importing the necessary module from IronXL, a license key is provided to authenticate the usage of the library. You can purchase your free license key from the IronXL trial license. The Load method is then employed to open an Excel workbook named "test_excel.xlsx". This workbook could contain various sheets with data or formatting. By loading it into the script, you gain the ability to manipulate its contents programmatically. This includes tasks like reading data, modifying cell values, or creating entirely new sheets. The library supports various file formats including XLSX, XLS, XLSM, XLTX, CSV, and TSV, making it versatile for handling different types of Excel files seamlessly.

Select Excel Worksheet

The next step is to select the worksheet we want to work on. The following code will specify the Excel spreadsheet.

# Select worksheet at index 0
worksheet = workbook.WorkSheets[0]
# Select worksheet at index 0
worksheet = workbook.WorkSheets[0]
PYTHON

The above line selects the worksheet at index 0 from the loaded Excel workbook, assigning it to the variable worksheet. In Excel, worksheets are individual tabs within a workbook where you can organize and manipulate data. By referencing the worksheet at index 0, you're accessing the first worksheet in the workbook, as indexing in Python typically starts from 0. This allows you to perform operations specific to that particular sheet, such as reading data, modifying cell values, or applying formatting.

Merge specific cells in an Excel file

Now that we have loaded the workbook and selected the worksheet, let's define the specific range of cells to merge. Within our selected worksheet, there's a column containing country names. For certain customers, the country value is the same, such as 'United States'. We'll merge cells in Excel for these specific instances. The following code will perform merge operations for a particular range.

# Merge cells within specified ranges
worksheet.Merge("E5:E7")
worksheet.Merge("E9:E10")

# Save workbook to retain changes
workbook.Save()
# Merge cells within specified ranges
worksheet.Merge("E5:E7")
worksheet.Merge("E9:E10")

# Save workbook to retain changes
workbook.Save()
PYTHON

These lines of code utilize the Merge method to combine cells within the selected worksheet. The first line merges cells in the range from E5 to E7, likely for consolidating data related to the "United States" in the country column. Similarly, the second line merges cells from E9 to E10, for another set of data entries with the same country value. After merging, the Save method is called to save the changes made to the workbook. This action ensures that the merged cells are retained in the Excel file.

The Merge method is used to merge a range of cells. This action combines the cells without erasing any existing values or data. However, only the value of the first cell in the merged cell region will be displayed. Nonetheless, the values of the merged cells remain accessible in IronXL.

Merged cells can be seen in the given output.

How to Merge Cells in an Excel File Using Python: Figure 2 - Python Merge Cells Excel

Retrieve Merged Regions

Merged regions in Excel refer to contiguous blocks of merged cells that have been combined into a single cell. Retrieving merged regions programmatically allows for the identification and handling of these areas within a worksheet. This information is useful for various tasks such as data analysis, formatting adjustments, or ensuring accurate data manipulation across merged cells. The following code will retrieve merged regions from an Excel worksheet.

# Print merged regions in the worksheet
print("Merged Regions are:")
retrieveMergedRegions = worksheet.GetMergedRegions()
for mergedRegion in retrieveMergedRegions:
    print(mergedRegion.RangeAddressAsString)
# Print merged regions in the worksheet
print("Merged Regions are:")
retrieveMergedRegions = worksheet.GetMergedRegions()
for mergedRegion in retrieveMergedRegions:
    print(mergedRegion.RangeAddressAsString)
PYTHON

The above code first prints a header indicating the start of the output related to merged regions. It then retrieves all the merged regions from the specified worksheet using the GetMergedRegions() method and iterates over each merged region. Within the loop, it prints the address of each merged region as a string using RangeAddressAsString. This provides a clear list of all merged regions in the worksheet, aiding in tasks such as identifying merged areas for data analysis, formatting adjustments, or targeted operations within the Excel file.

The previously merged cells are:

How to Merge Cells in an Excel File Using Python: Figure 3 - Merged Region Output

Unmerge cells in Excel file

Unmerging cells in an Excel file involves reversing the process of merging and separating previously combined cells into individual cells. To unmerge cells in an Excel file using IronXL, you can use the Unmerge method. Here's how you can do it:

# Unmerge cells within specified ranges
worksheet.Unmerge("E5:E7")
worksheet.Unmerge("E9:E10")

# Save workbook to retain changes
workbook.Save()
# Unmerge cells within specified ranges
worksheet.Unmerge("E5:E7")
worksheet.Unmerge("E9:E10")

# Save workbook to retain changes
workbook.Save()
PYTHON

In the above code snippet, the Unmerge method is used to unmerge the cells within the specified ranges, specifically targeting the ranges E5:E7 and E9:E10. This action restores the individuality of cells within these ranges, allowing for independent manipulation of their contents. Finally, the Save method is invoked to ensure that the changes are reflected and persisted in the Excel workbook.

How to Merge Cells in an Excel File Using Python: Figure 4 - Unmerge result file

Conclusion

In conclusion, Python, in combination with IronXL, simplifies the task of merging cells in Excel, enhancing data organization and visualization efforts. IronXL's extensive capabilities, rich features, and user-friendly interface empower users to seamlessly manipulate Excel files, from loading workbooks to merging specific cell ranges programmatically. With a free trial available for exploration and a comprehensive licensing option, IronXL offers a compelling solution for professionals seeking efficient data management in Python applications.

常见问题解答

如何使用 Python 在 Excel 中合并单元格?

您可以使用 IronXL 库通过 Python 在 Excel 中合并单元格,方法是加载工作簿和工作表,然后将 Merge 函数应用于所需的单元格范围,例如 worksheet.Merge('A1:B2')

使用 Python 是否可以在 Excel 中取消合并单元格?

是的,使用 IronXL,您可以应用 Unmerge 方法取消合并 Excel 中的单元格,例如 worksheet.Unmerge('A1:B2')

合并单元格的步骤是什么?

要使用 IronXL 合并单元格,请首先安装库,加载您的 Excel 工作簿,选择工作表,并将 Merge 函数应用于您要合并的特定单元格范围。

IronXL 可以识别 Excel 表中的合并单元格区域吗?

是的,IronXL 可以使用 GetMergedRegions() 方法识别合并的单元格区域,该方法提供工作表中合并区域的列表。

IronXL 为在 Python 中操作 Excel 文件提供了哪些好处?

IronXL 提供了跨平台兼容性、支持各种 Excel 格式、直观的 API 来读写数据、样式化单元格以及使用公式进行计算等好处。

如何在 Python 项目中安装 IronXL?

您可以使用 pip 命令在您的 Python 项目中安装 IronXL:pip install ironxl

IronXL 是否支持多种 Excel 文件格式?

是的,IronXL 支持包括 XLSX、XLS、XLSM、XLTX、CSV 和 TSV 在内的多种 Excel 文件格式,使其在不同的数据管理需求中具有多样性。

我可以在购买许可证之前试用 IronXL 吗?

是的,IronXL 提供免费试用,可以让用户在决定购买许可证之前探索其功能和能力。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。