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

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

我不明白为什么我的代码不是 运行,我对 python 不太了解,但这看起来很基本,我正在考虑 firstRow 是一个数组,我说的对吗?另外,我实现了新的 excel 文件,而 first 不为空(如果我清楚地了解如何检查它是否为空)。谢谢

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

检查下面的循环:

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

我们永远不会退出 while first: 循环,因为总是有一个 first 并且它永远不会改变。我们先打开循环,for first in firstRow:

1) first is the value of A1 in your workbook

2) Now we loop while first

3) We write first to the cell at number, 0 which is 0, 0

4) Increment number and repeat while first again.

5) Now write first again to the cell at number, 0 which now is 1, 0

6) Increment number and repeat while first again.

您可以看到我们如何永远无法摆脱这个循环,您的程序无休止地将 first 写入新单元格。

您可能想使用:

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