Python循环不工作(xlwt)

我在Python中有这段代码,应该工作。

python import xlwt #== change variables according to requirements ==# numoftopcol = 5 numoftestcases = 4 coltext = ['Test Case', 'Test Name', 'Duration', 'Factual Result', 'Result (Pass/Fail)'] testN = ['void','Get Counter Result', 'Read Stats', 'Client Initialization', 'Start Server'] #== change variables according to requirements ==# styleH = xlwt.easyxf('font: name Arial, bold on, color-index blue;') styleH.font.height = 400 stylee = xlwt.easyxf('font: name Arial') wb = xlwt.Workbook() ws = wb.add_sheet('Test Case Overview') c = 0 numoftopcol += 1 for c in range(c,numoftopcol): ws.write(0, c, coltext[c], styleH), ws.col(c).width = 7000 import random c = 1 numoftestcases += 1 for c in range(c,numoftestcases): strC = str(c), ws.write(c,0,'TC-'+strC,stylee), ws.write(c,1,testN[c],stylee), ws.write(c,2,'DUR',stylee), ws.write(c,3,'RandomStr',stylee), randomint = random.randint(0,1), if randomint == 0: ws.write(c,4,'PASS',stylee) else: ws.write(c,4,'FAIL',stylee) 

现在,第一个周期工作正常(styleH)。 第二个不工作(stylee)。 debugging我发现,c = 1和numoftestcases = 5。 所以如果c <numoftestcases或1 <5,那么周期应该是正常的,对吧?

显然它没有。 我在cmd中得到以下错误输出(第二个周期)。

forTraceback(最近调用的最后一个):在IndexError:列表索引超出范围的文件“”,第2行

Traceback(最近调用最后一个):TypeError中的文件“”,第3行:不能连接“str”和“tuple”对象

这有什么问题? 早先这个工作我记得。 我没有改变循环代码,但现在不工作。

我也尝试在第二个周期的第一行中放置一个打印(c),输出只有1.没有更多的数字跟在后面。

检查xls文件,只有第一个周期写在电子表格中。

我将这些代码存储在一个文本文件中,以便我可以随时在cmd中调用这个命令。

首先:索引超出范围:你将numoftopcol定义为5,这是列表的len ,但是在循环之前,你增加它…现在访问这个索引产生超出范围…

错误的根本原因是Excel的坐标从1开始,但Python列表是从0开始的。 我会做从0n循环,只为xlwt调用添加1,而不是做所有你正在做的+1东西。

第二:连接错误:你没有发布任何堆栈跟踪,但

 strC = str(c), 

创build一个tuple 。 而下一行:

  ws.write(c,0,'TC-'+strC,stylee), 

试图添加一个str到一个tuple

我发现了什么问题。 我不得不将cnumoftestcases的数据types转换为int。

 int(c) int(numoftestcases) 

案件解决。 现在正在工作。