Iterate through worksheets in workbook- Python Nested For loop
<p>I am trying to open an excel workbook and iterate through each of the worksheets in a loop. Here is first loop:</p>

<pre><code>wb = openpyxl.load_workbook('snakes.xlsx')
for i in wb.worksheets: 
    i= 0
    wb.get_sheet_names()
    i = i + 1
</code></pre>

<p>Once I can successful go through each one of these worksheets, i would like to do a nested loop which takes each one of my png files and places them in the worksheets. It is important to note that the sheet names and the png files have the same names (country names) stored in a dataframe called country_names. </p>

<p>Second loop:</p>

<pre><code>for ws in wb.worksheets: 
    img = openpyxl.drawing.image.Image(folder + str(var) + '.png')
    ws.add_image(img, 'K1')
    wb.save('snakes.xlsx')
</code></pre>

<p>Any ideas on how to do the nested for loop so the code loops through the images and write them to the worksheets?</p>

<p>Your code snippets seem to show a fundamental misunderstanding of how the <code>for</code> loop works in Python.</p>

<p>To loop through each sheet, you were on the right track:</p>

<pre><code>wb = openpyxl.load_workbook('test.xlsx')
for sheet in wb.worksheets:
    # do stuff with "sheet"
    pass
</code></pre>

<p>The variable in the <code>for</code> loop (<code>sheet</code> in my example, <code>i</code> in yours) is the member of the list (<code>wb.worksheets</code>): it is not an integer index. In your example, you immediately overwrite the value of <code>i</code> with 0 in <em>every loop</em> and thus do not have a sheet to work with. </p>

<p>It is also worth noting <code>get_sheet_names()</code> is called from the workbook object, so there is no need to call it within the for loop:</p>

<pre><code>&gt;&gt;&gt; wb.worksheets
[&lt;Worksheet "Sheet1"&gt;, &lt;Worksheet "Sheet2"&gt;, &lt;Worksheet "Sheet3"&gt;]
</code></pre>

<p>Finally, your second "nested for loop" (which isn't even nested) is correct, except it saves the new Excel file every loop, which is wasteful. </p>

<p>Since you indicate that the worksheet name is the same as PNG name, you can just call the attribute <code>title</code> for the worksheet when finding the image. </p>

<p>Below should be a working example:</p>

<pre><code>wb = openpyxl.load_workbook('snakes.xlsx')
for ws in wb.worksheets: 
    img = openpyxl.drawing.image.Image(ws.title + '.png')
    ws.add_image(img, 'K1')
wb.save('new.xlsx')
</code></pre>

python for-loop openpyxl