#๐ my code wont save the dropdowns list ( data validation ) from excel to another
9 messages ยท Page 1 of 1 (latest)
@wraith coral
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
openpyxl does have support to write data validations, at least:
https://openpyxl.readthedocs.io/en/stable/validation.html
I don't know about reading them, though... so making a copy of a validation might be tricky.
Oh, well someone had the same question on SO: https://stackoverflow.com/a/71160128
from copy import copy
for validation in templateSheet.data_validations.dataValidation:
newSheet.add_data_validation(copy(validation))
Something like that.
@wraith coral
Assuming that the method above could work, perhaps the validations are already gone by the time you're written contents to the active worksheet.
It looks like you're opening the template, retrieving the worksheet, then modifying it, and saving the changed workbook to a new path.
So by the time you run self.transfer_data_validation, those validations may be gone.
Try to store them somewhere first, then write them again later:
class ExcelPopulator:
def __init__(self, template_path):
self.template_path = template_path
self.verify_template_path()
self.validations = []
def _store_validations(self, source_ws):
self.validations = [copy(dv) for dv in source_ws.data_validations.dataValidation]
def _write_validations(self, target_ws):
for dv in self.validations:
target_ws.add_data_validation(dv)
def populate_excel(self, user_name, purchases, output_path, statement_period=None):
workbook = load_workbook(self.template_path)
sheet = workbook.active
self._store_validations(sheet)
# ...
self._write_validations(sheet)
workbook.save(output_path)
Welp, gave it a try. ๐
Don't think I can be much more help on this one, then. Apologies.
Might try on some smaller examples, one workbook with validations and just load_workbook then workbook.save(new_path). See if the above method for copying validations actually works, and if so then find where in your current code that appears to break down.
Not really, I'm afraid. I don't work with Excel that much.
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.