简体   繁体   中英

Not able to export data into Excel using xlsxwriter library

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()

我认为这是您想要实现的目标

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

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 :

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM