weber1215
weber1215

Reputation: 21

How to include the cell's value in the Excel file name with Python?

The existing Excel file name is test.xlsx. Let's say the value of D3 cell is 333. (This value varies from month to month, with many files.) I'm trying to include the value of D3 cell in the file name. The result must be 'test 333.xlsx'. I made the following code. But the resulting file name is 'wb,c.value.xlsx'. It seems to have been taken only as a string. How can I make 'test 333.xlsx' in an automatic way?

from openpyxl import load_workbook
wb = load_workbook('test.xlsx')
ws = wb["sheet01"] 
c = ws['D3'] 
wb.save("wb,c.value.xlsx")

Upvotes: 2

Views: 1641

Answers (1)

k88
k88

Reputation: 1934

You are writing the file as a string with the name "wb,c.value.xlsx", so the variables wb and c are not read and instead the string "wb,c" is parsed in. You can put a variable name in a string either as

wb.save(f"{wb} {c.value}.xlsx")

or something like

filename = str(wb) + " " + str(c.value) + ".xlsx"
wb.save(filename)

That said I am not familiar with openpyxl, so I am not sure if wb and c.value have a string interpration.

Upvotes: 1

Related Questions