Traceback (most recent call last): File "C:\Users\Felix\Desktop\新建文件夹\ZZZ.py", line 19, in <module> cell.value = None ^^^^^^^^^^ AttributeError: 'MergedCell' object attribute 'value' is read-only
This error message indicates that you are trying to modify the value of a merged cell in a spreadsheet, but the 'value' attribute of the 'MergedCell' object is read-only. This means that you cannot directly modify the value of a merged cell using the 'value' attribute.
To modify the value of a merged cell, you need to modify the value of the individual cells that make up the merged cell. You can access the individual cells using the 'merged_cells' attribute of the worksheet object, which returns a list of all merged cell ranges in the worksheet.
Here is an example code snippet that demonstrates how to modify the value of a merged cell by modifying the value of the individual cells that make up the merged cell:
import openpyxl
# Load the workbook
workbook = openpyxl.load_workbook('example.xlsx')
# Select the worksheet
worksheet = workbook['Sheet1']
# Get the merged cell object
merged_cell = worksheet['A1']
# Get the coordinates of the merged cell
start_row, start_column, end_row, end_column = merged_cell.bounds
# Loop through the individual cells that make up the merged cell
for row in range(start_row, end_row+1):
for column in range(start_column, end_column+1):
# Get the cell object
cell = worksheet.cell(row=row, column=column)
# Modify the value of the cell
cell.value = None
# Save the workbook
workbook.save('example.xlsx')
In this example, we first load the workbook and select the worksheet that contains the merged cell we want to modify. We then get the merged cell object and the coordinates of the merged cell using the 'bounds' attribute.
Next, we loop through the individual cells that make up the merged cell using the 'range' function and the start and end coordinates of the merged cell. For each cell, we get the cell object using the 'cell' method of the worksheet object and modify its value to None.
Finally, we save the workbook to persist the changes.
cell.value = None
^^^^^^^^^^
AttributeError: 'MergedCell' object attribute 'value' is read-only" title="Traceback (most recent call last):
File "C:\Users\Felix\Desktop\新建文件夹\ZZZ.py", line 19, in 原文地址: https://www.cveoy.top/t/topic/Ajd 著作权归作者所有。请勿转载和采集!