简体   繁体   English

无法使用 xlsxwriter 库将数据导出到 Excel

[英]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).我正在尝试迭代一个 For 循环,以便将两个列表中的元素导出到 A 列和 B 列中的 excel。但是,每当我运行代码时,它只会在 B 列第 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这就是我在运行代码时在 excel 文件中得到的内容

#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.考虑给定的列表 => prod_codes,ID_codes。 The below code will write each list as a column in an excel sheet.下面的代码会将每个列表写为 excel 表中的一列。 The parameters of worksheet.write() are as shown below worksheet.write()的参数如下图

worksheet.write(row_number,column_number,value_to_be_written) 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.请通过官方文档 go ,清楚如何执行您需要执行的操作。 https://xlsxwriter.readthedocs.io/working_with_data.html https://xlsxwriter.readthedocs.io/working_with_data.html

You have a silent syntax error in your code with i =+ 1 instead of i += 1 .您的代码中有一个静默语法错误,使用i =+ 1而不是i += 1 The code translates to i = +1 which is equivalent to i = 1 so it doesn't iterate.代码转换为i = +1相当于i = 1所以它不会迭代。

Here is an alternative way to structure you code with enumerate() and the (row, col) syntax of worksheet.write() :这是使用enumerate()worksheet.write()的 (row, col) 语法构建代码的另一种方法:

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 : Output

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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