Python: open an existing Excel file and count lines in a worksheet

I have an excel file. I want to load this one and get the number of lines on this sheet so that I can write on the next line of this sheet later and save it again. I get the following error messages:

AttributeError: 'Worksheet' object has no attribute 'nrows'

But it’s clear that this method exists because everyone uses it to get an account. The code I wrote is as follows:

def write_xls_result(test_case):
    testCase = re.sub("/", "_", test_case)
    automation_report = os.path.expanduser("~/Library/pathtofile/UITests.xctest/Contents/Resources/Automation_Result.xls")
    if os.path.isfile(automation_report):

        w = copy(open_workbook(automation_report))
        copy_sheet = w.get_sheet(0)
        col_width = 256 * 30

        try:
            for i in itertools.count():
                copy_sheet.col(i).width = col_width
        except ValueError:
            pass

        for row in range(copy_sheet.nrows):
             print '{} {}'.format("Row COUNT",copy_sheet.nrows)

        row_index = 10
        copy_sheet.write(row_index,0, testCase)
        w.save('Automation_Result.xls')
        row_index += 1
        print '{} {}'.format("RRRROOOOWWWWW",row_index)

    else:

So, I tried another approach:

def write_xls_result(test_case):
    testCase = re.sub("/", "_", test_case)
    automation_report = os.path.expanduser("~/Library/pathtofile/UITests.xctest/Contents/Resources/Automation_Result.xls")
    if os.path.isfile(automation_report):
        workbook = xlrd.open_workbook(automation_report)
        result_sheet = workbook.get_sheet(0)
        rowcount = result_sheet.nrows
        print '{} {}'.format("Row COUNT",rowcount)

        col_width = 256 * 30

        try:
            for i in itertools.count():
                result_sheet.col(i).width = col_width
        except ValueError:
            pass

        row_index = 10
        result_sheet.write(row_index,0, testCase)
        workbook.save('Automation_Result.xls')
        row_index += 1
        print '{} {}'.format("RRRROOOOWWWWW",row_index)

    else:

And I get this error:

raise XLRDError("Can't load sheets after releasing resources.")
xlrd.biffh.XLRDError: Can't load sheets after releasing resources.

I'm still new to python, maybe I'm just doing something wrong. Some help or tips would be good. thank

+4
source share
2 answers

-, xlrd xlrd.open_workbook...

result_sheet , :

result_sheet = workbook.sheet_by_index(0)

( .get_sheet)

? xlrd? .width ( , , list) , .

, 10? , else 11.

+5

, , :

w.save('Automation_Result.xls')

:

workbook.save('Automation_Result.xls')

workbook xlrd, .

+2

Source: https://habr.com/ru/post/1536630/


All Articles