简体   繁体   English

无法将我的标头从excel写入python中的另一个excel

[英]Can't write my headers from an excel to another excel in python

I can't get why my code isn't running, I don't know big thing about python but that seems pretty basic, I'm considering the firstRow is an array, am I right? 我不明白为什么我的代码无法运行,我不了解python的重要知识,但这似乎很基本,我正在考虑firstRow是一个数组,对吗? Also, I implement my new excel file while first is not empty (if i clearly understood how to check if it's empty or not).. Thank you 另外,我会在first不为空的情况下实现我的新excel文件(如果我清楚地知道如何检查它是否为空)。.谢谢

import xlsxwriter
import xlrd

#ouvre l'excel
workbook = xlrd.open_workbook('myExcel.xlsx', on_demand = True)

#utilise le 2nd spreadsheet
worksheet = workbook.sheet_by_index(1)

#recupere la premiere ligne (headers) // a priori un array
firstRow = worksheet.row_values(0)


# Create an new Excel file and add a worksheet.
workbook2 = xlsxwriter.Workbook('demo2.xlsx')
worksheet2 = workbook2.add_worksheet()

number = 0

#pour chaque colonne, l'écrire dans une nouvelle colonne du fichier excel
for first in firstRow:
    while first:
        worksheet2.write(number, 0, first)
        number += 1

workbook2.close()

Examine the loop below: 检查以下循环:

for first in firstRow:
    while first:
        worksheet2.write(number, 0, first)
        number += 1

We never exit the while first: loop because there is always a first and it is never changed. 我们永远不会退出while first:循环,因为总会有first ,而且永远不会改变。 We first open the loop, for first in firstRow : 我们首先断开环路,为firstfirstRow

1) first is the value of A1 in your workbook 1) first是工作簿中A1的值

2) Now we loop while first 2)现在我们循环while first

3) We write first to the cell at number , 0 which is 0, 0 3)我们写first到在细胞number00, 0

4) Increment number and repeat while first again. 4)增量number和重复while first一次。

5) Now write first again to the cell at number , 0 which now is 1, 0 5)现在, first再次写入单元格number 0 ,现在是1, 0

6) Increment number and repeat while first again. 6)增量number和重复while first一次。

You can see how we'll never get out of this loop, your program endlessly writes first into a new cell. 您会看到我们将永远无法摆脱这个循环,您的程序会无休止地first写入新的单元格。

You may want to use: 您可能要使用:

for first in firstRow:
    worksheet2.write(number, 0, first)
    number += 1

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

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