output python dataframe to excel and create a new data_validation column in the exported excel sheet


i have a dataframe that i want to export into an excel workbook. i want the excel to have an additional column (that is not in the dataframe) that is a data validated column in the workbook – i want it to only take in the range 1-9.

dataframe looks something like this:

name year
trixie 1985
timmy 1990
chester 1993

I want the exported excel sheet to look like this: where the code column only allows a number between 1 and 9 (the excel data validation way) I want to do all of this in python.

name year code
trixie 1985
timmy 1990
chester 1993

Please help. THANKS in advance!

Asked By: codingrainha



Just assign a new column before exporting to excel:

df.assign(code='').to_excel('file.xlsx', index=False)

It’s not possible to apply some constraints on the columns (without pain) in Python. Maybe you can use a macro or openpyxl to write an xlsm file.

Answered By: Corralien

I would use pandas.ExcelWriter with worksheet.data_validation from :

df["code"] = None
items = list(range(1,10))
max_row, max_col = df.shape

with pd.ExcelWriter("/tmp/file.xlsx") as writer:
    df.to_excel(writer, index=False, sheet_name="Sheet1", startrow=0)
    wb = writer.book
    ws = writer.sheets["Sheet1"]
    ws.data_validation(f"C2:C{str(max_row+2)}", {"validate": "list", "source": items})

Output :

enter image description here

Answered By: Timeless
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.