1

I'm trying to iterate a For Loop such that the elements in the two lists get exported to excel in columns A and B. However, whenever I run the code it only displays a single number in column B row 1 (B1).

The entire code is too long so I'm attaching just a snippet of the code where I am stuck.

This is what I'm getting in my excel file when I run the code

#Exporting data to Excel
workbook = xlsxwriter.Workbook('efficient_front.xlsx')
worksheet = workbook.add_worksheet()

i = 1
if company == first_company:
    for perc_return in returns:
        worksheet.write('A' + str(i) , perc_return)
        i =+ 1
else:
    for perc_return in returns:
        worksheet.write('B' + str(i), perc_return)
        i =+ 1

workbook.close()

2 Answers 2

3

I assume this is what you wanted to achieve

consider the given lists => prod_codes, ID_codes. The below code will write each list as a column in an excel sheet. The parameters of worksheet.write() are as shown below

worksheet.write(row_number,column_number,value_to_be_written)

    prod_codes = [1001,1002,1003,1004,1005,1006]
    ID_codes = [123,345,567,789,908,345]
    with xlsxwriter.Workbook('PATH for XLSX to be created') as workbook:
            worksheet = workbook.add_worksheet("NAME_ME")
            for index,value in enumerate(ID_codes):
                   worksheet.write(index,0,value)
            
            for index,value in enumerate(prod_codes):
                   worksheet.write(index,1,value)

Please go through the official documentation, it's clear how to perform what you need to perform. https://xlsxwriter.readthedocs.io/working_with_data.html

Sign up to request clarification or add additional context in comments.

Comments

0

You have a silent syntax error in your code with i =+ 1 instead of i += 1. The code translates to i = +1 which is equivalent to i = 1 so it doesn't iterate.

Here is an alternative way to structure you code with enumerate() and the (row, col) syntax of worksheet.write():

import xlsxwriter

workbook = xlsxwriter.Workbook('efficient_front.xlsx')
worksheet = workbook.add_worksheet()

returns = [1, 2, 3, 4, 5]
company = True
first_company = False

if company == first_company:
    col_num = 0
else:
    col_num = 1

for row_num, perc_return in enumerate(returns):
    worksheet.write(row_num, col_num, perc_return)

workbook.close()

Output:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.