简体   繁体   English

python xlwt尝试覆盖现有工作表,而不是创建新工作表

[英]python xlwt tries to overwrite existing sheet rather than create new sheet

I have a simple app with a GUI that takes in a number of presets, runs some tests on them, and saves the results to an excel sheet. 我有一个带有GUI的简单应用,该GUI可以接受许多预设,对其进行一些测试,然后将结果保存到excel工作表中。 My problem is, each time I change the presets and hit the button, the program attempts to overwrite the data that was created in the last test, rather than create a new sheet like I want it too. 我的问题是,每次更改预设并按下按钮时,程序都会尝试覆盖上次测试中创建的数据,而不是像我想要的那样创建新的工作表。 Here is some code. 这是一些代码。

data_book = xlwt.Workbook( encoding = "utf-8" )

def TEST():
    ### Irrelevant code that does a few calculations ###



    # Prepare data storage

    #data_book = xlwt.Workbook( encoding = "utf-8" ) commented out, same code outside of function 

    sheet = data_book.add_sheet( str( loc ) + "N"+ str( N ) + "d" + str( dis ) ) #names the sheet using values from UI
    sheet.write( 0, 0, "Title" ) #title the sheet
    for i in range( 10 ): #small number for debugging
        for a2 in A2:
            sheet.write( i+1, 3, a2 )
            sheet.write( i+1, 2, eng.test( wav_arr[ i ], A1, a2, N ) ) 
            sheet.write( i+1, 1, txt_arr[ i ] ) 
            sheet.write( i+1, 0, dt.now() ) 
    # Save sheet to workbook       
    data_book.save( "test"+str( d.today() )+".xls" )
    print "data saved. Test complete."
    clear( master_arr )

# this is the button, calls the test when pressed
b = Button( master, text = "Test!", command = lambda: TEST() )
b.pack()

I am not sure how to overcome this. 我不确定如何克服这个问题。 As you can see, I have tried moving the creation of data_book inside the TEST() function, but that didn't help. 如您所见,我尝试在TEST()函数中移动data_book的创建,但这没有帮助。 Maybe a try-except block that explicitly creates a new sheet when the overwrite exception rises? 也许try-except块会在覆盖异常增加时显式创建一个新工作表? But I thought I already explicitly create a new sheet when the button is clicked. 但是我认为单击按钮时已经明确创建了一个新工作表。 I appreciate your help. 我感谢您的帮助。

I solved this issue. 我解决了这个问题。 For whoever is interested, look at the nested for-loop around the sheet.write() functions. 对于感兴趣的人,请查看sheet.write()函数周围的嵌套for循环。 Notice that the way the index is set up, the function is commanded to write to the same cells for every value in the array A2. 请注意,建立索引的方式是,命令该函数针对数组A2中的每个值写入相同的单元格。 This causes an exception as the program attempts to overwrite cells. 当程序尝试覆盖单元格时,这将导致异常。

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

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