我正在尝试编写一个脚本,可以一次提取一行excel并打印出来。我想使用一种方法来更改行。我可以得到要更改的行的值(变量rrowx),但是当我打印currentRow字符串时,我得到的是原始行,而不是新调整的行。你知道吗
import xlrd
class Loader(object): ## engine to load and unload spread sheets
## then sets them to a variable
# set the variables
workbook = " " # name of the file
sheetCount = 0 # amount of sheets in the spreadsheet
sheetNumber = 0 # current sheet (index)
rowCount = 0 # amount of rows in the spreadsheet
currentSheet = " " # name of current sheet
topRow = " " # row 0 string
currentRow = " " # row x string
global rrowx
rrowx = 0
# begin the load
workbook = xlrd.open_workbook('test.xlsx')
sheetCount = workbook.nsheets
sheetNames = workbook.sheet_names()
currentSheet = workbook.sheet_by_index(sheetNumber)
#topRow = currentSheet.row_values(rowx=rrowx, start_colx=scolx, end_colx=ecolx)
currentRow = currentSheet.row_values(rowx=rrowx)
# methods to navigate the sheet
def nextrow(self):
global rrowx
print(rrowx)
rrowx += 1
print(rrowx)
return rrowx
spreadsheet = Loader()
## Debuggin prints
print(spreadsheet.sheetNames)
print(spreadsheet.sheetCount)
print("What Sheet would you like to use? (Use numbers)")
spreadsheetadjust = int(input()) # takes input as a interger
spreadsheet.currentSheet = spreadsheetadjust - 1 # takes input and -1 for index value
print ('Current sheet name: %s' % spreadsheet.currentSheet)# prints current sheet name
print('top row:')
#print(spreadsheet.topRow)
print('row 1 ')
print(spreadsheet.currentRow)
print("NextRow")
spreadsheet.nextrow()
print(spreadsheet.currentRow)
我想在更改了rowx变量并再次调用currentRow上的print之后,将更改打印的行。但是我得到的是两次打印同一行,尽管我可以看到rorowx的值随着我在方法中添加的打印而改变。你知道吗
披露:我只做了一个月的编程,所以很抱歉,如果这是一个简单的答案,我只是错过了。你知道吗
我强烈建议您阅读python面向对象基础知识。您的代码有多个问题,我将提到一些:
您的类变量是类变量,意味着 类将共享相同的变量。所以如果你创造了多个 在类的实例中,您将获得意外/不希望的行为。
不建议使用
global
变量,尤其是在 我可以不用它。您不需要在python中初始化变量
在您的实现中
spreadsheet.currentSheet = spreadsheetadjust - 1
即使修复了,也会导致失败 你的问题。你想要什么spreadsheet.sheetNumber = spreadsheetadjust - 1
下面是正确使用python类的代码:
相关问题 更多 >
编程相关推荐