The ClearHyperlinks member of the Range object in the Excel object model is a method used to remove all hyperlinks from a specified range of cells. When working with Excel files via xlwings in Python, this functionality is particularly useful for cleaning up data, preparing ranges for new hyperlinks, or simply removing unwanted links that may interfere with data processing or presentation. It operates by clearing the hyperlink formatting and the underlying link address, leaving the cell’s display text (if any) intact as plain text.
Syntax in xlwings:
In xlwings, the ClearHyperlinks method is accessed through a Range object. The syntax is straightforward, as it does not require any parameters. The general format is:
range_object.clear_hyperlinks()
Here, range_object is an instance of xlwings.Range, representing the cell or range of cells from which hyperlinks are to be removed. The method applies to all cells within that range, and if no hyperlinks are present, it has no effect.
Example Usage:
Consider an Excel workbook where a worksheet contains various hyperlinks in cells A1 through A10, linking to external websites or internal documents. To remove all these hyperlinks using xlwings, you can execute the following code:
import xlwings as xw
# Open the workbook and specify the worksheet
wb = xw.Book('example.xlsx')
sheet = wb.sheets['Sheet1']
# Define the range containing hyperlinks
target_range = sheet.range('A1:A10')
# Remove all hyperlinks from the range
target_range.clear_hyperlinks()
# Save and close the workbook (optional)
wb.save()
wb.close()
Leave a Reply