I'm trying to modify an excel file using openpyxl.
The modifying part works, but after saving the changes all the dropdown lists/menus disappear. With dropdown lists/menus I mean that some columns have set options such as column A is for gender and has options Man or Woman. Is there a way to save the excel file with the included dropdown menus/lists in the correct columns?
I've tried to use ChatGPT but using data validation functions either gives me an error or still leave me with an excel file without these dropdown menus. Does anyone have an idea how I could fix this?
edit:
The code I used to modify certain cells is given below:
og_wb=load_workbook(f"C:/Users/{os.getlogin()}/Documents/B&B Post/Grondenlijst 2024.xlsx")workbook=load_workbook(f"C:/Users/{os.getlogin()}/Documents/B&B Post/Grondenlijst 2024.xlsx")worksheet=workbook['2023 Gronden - Pro forma']# Find the correct row based on your conditionfor row in worksheet.iter_rows(min_row=3, max_row=worksheet.max_row, min_col=1, max_col=worksheet.max_column): # Your code here if row[2].value == bsn: # Update the value in the desired column of the correct row worksheet.cell(row=row[0].row, column=6, value=kolom_F) worksheet.cell(row=row[0].row, column=8, value=kolom_H) if row[4].value=='Stukken ontvangen?': worksheet.cell(row=row[0].row, column=5, value='Ontvangstbevestiging?')And the code ChatGPT gave me to 'copy' these data validation cells is given by:
columns_with_validation = ['A', 'E', 'H'] for column in columns_with_validation: # Retrieve data validation settings for the column for row in range(1, worksheet.max_row + 1): cell = worksheet[column + str(row)] print(type(cell)) if hasattr(cell, 'data_validation') and cell.data_validation is not None: # Create a new data validation object and copy settings dv_copy = DataValidation(type=cell.data_validation.type) dv_copy.formula1 = cell.data_validation.formula1 dv_copy.formula2 = cell.data_validation.formula2 dv_copy.showDropDown = cell.data_validation.showDropDown dv_copy.errorTitle = cell.data_validation.errorTitle dv_copy.error = cell.data_validation.error dv_copy.errorStyle = cell.data_validation.errorStyle dv_copy.promptTitle = cell.data_validation.promptTitle dv_copy.prompt = cell.data_validation.prompt dv_copy.promptStyle = cell.data_validation.promptStyle # Apply data validation to the same cell in the new Excel file worksheet.add_data_validation(dv_copy) dv_copy.add(cell)The problem however is that these cells do not have attribute data_validation