Reputation: 4418
I have excel template that has multiple sheets with US States (MTHLY-CA...etc)
I also have a dataframe that has columns StateID
and premiumtest
The idea is to loop through worksheet names and compare it to column StateID in a dataframe. And if states matches then write premiumtest
value into particular cell in a template.
import openpyxl
# getting workbook
wb = openpyxl.load_workbook(r'\server\user\Python\Template.xlsx')
# looping through worksheets
for sheet in wb.worksheets:
sheetnames = sheet
print(sheetnames)
for index, row in df.iterrows():
if any(x in 'MTHLY-'+ row[0] for x in sheetnames): #[0]is the index for column StateID
# Then write premiumtest into cell 1
But I got an error:
Traceback (most recent call last):
if any(x in 'MTHLY-'+ row[0] for x in sheetnames): #
File "x:\Documents\Python\Treaty Year Report\TreatyYearReport3 - Copy.py", line 68, in <genexpr>
if any(x in 'MTHLY-'+ row[0] for x in sheetnames): #
TypeError: 'in <string>' requires string as left operand, not tuple
print(sheetnames): .
Upvotes: 0
Views: 153
Reputation: 25554
to get your code
any(x in 'MTHLY-'+ row[0] for x in sheetnames)
running properly, you could obtain the sheets names as
sheetnames = [sheet.title for sheet in wb.worksheets]
that would basically replace your current for loop
for sheet in wb.worksheets:
sheetnames = sheet
print(sheetnames)
Upvotes: 2
Reputation: 27485
You are comparing a single worksheet object to a string. This is the issue. In the code below you're looping through each sheet then overritting the sheetnames
variable.
for sheet in wb.worksheets:
sheetnames = sheet
print(sheetnames)
You are looking to get is a list of the worksheet.title
so more something like this:
sheetnames = [sheet.title for sheet in wb.worksheets]
Upvotes: 2