#operating profit
year_list = []
for filename in name_list:
book = openpyxl.load_workbook(filename)
sheet = book.worksheets[0]
def findExistString(searchString, text):
if searchString in text: return True
else: return False
def findNonExistString(searchString, text):
if searchString in text: return False
else: return True
for row in sheet.rows:
if findExistString ("Sales", row[1].value):
year_list.append(filename[7:14])
break
So we extracted year_list. Out value is
['2011.12',
'2012.12',
'2013.12',
'2014.12',
'2015.12',
'2016.12',
'2017.12',
'2018.12',
'2019.12']
It came out like this. I put it in the "for" phrase and it didn't work. Below is the for-loop syntax
sheet1 = wb.active
file_name = 'Electric constant.xlsx'
sheet1.title = 'sampleSheet'
for coulumn_index in year_list:
sheet1.cell(row=1, column=coulumn_index).value = coulumn_index
wb.save(filename=file_name)
out
TypeError Traceback (most recent call last)
<ipython-input-68-380cc469c2fa> in <module>
3 sheet1.title = 'sampleSheet'
4 for coulumn_index in year_list:
----> 5 sheet1.cell(row=1, column=coulumn_index).value = coulumn_index
6
7 wb.save(filename=file_name)
~\anaconda3\lib\site-packages\openpyxl\worksheet\worksheet.py in cell(self, row, column, value)
233 """
234
--> 235 if row < 1 or column < 1:
236 raise ValueError("Row or column values must be at least 1")
237
TypeError: '<' not supported between instances of 'str' and 'int'
I tried running it with str(year_list)
but it didn't work
What I want to make is to select the year_list and list the data in Excel!
for coulumn_index in year_list:
sheet1.cell(row=1, column=coulumn_index).value = coulumn_index
If you look at the execution process in the
sheet1.cell(row=1, column='2011.12').value = '2011.12'
As you can see in the column, there is an error when comparing numbers and characters. I don't think it's the course of action you want.
It seems better to check the index of the column using the enumerate.
for idx, coulumn_index in enumerate (year_list):
sheet1.cell(row=1, column=idx).value = coulumn_index
Or you can check the index for the value in the entire list.
for coulumn_index in year_list:
sheet1.cell(row=1, column=year_list.index(coulumn_index)).value = coulumn_index
© 2024 OneMinuteCode. All rights reserved.