Search code examples
pythonexcelxlrd

Reading a cell value in Excel and write into an othet existing Excel file with python


I have a bunch of xls files in a given folder. I want to open them one by one get a given cell value and write into an other existing (half filled) excel file (in to a given place). Here is my code. It gives back an error for the row, which defines the place where I want to write the data. It says: AttributeError: 'Worksheet' object has no attribute 'range' Can you please help me?

for file in glob.glob('N:\*.xls'):
    fajlneve = str(file)
    fajlneve = fajlneve.decode('latin-1')
    book = xlrd.open_workbook(file, formatting_info=True, encoding_override="utf-8")
    sheets = book.sheet_names()
    for index, sh in enumerate(sheets):
        sheet = book.sheet_by_index(index)
        rows, cols = sheet.nrows, sheet.ncols
        for row in range(rows):
            for col in range(cols):
                # print "row, col is:", row+1, col+1,
                thecell = sheet.cell(row, col)
                ertek = thecell.value
                xfx = sheet.cell_xf_index(row, col)
                xf = book.xf_list[xfx]
                bgx = xf.background.pattern_colour_index
                pattern_colour = book.colour_map[bgx]
                if row == 19 and col == 11 and index == 1:
                    utkategoria = ertek
                    print utkategoria
                    wb = load_workbook(
                        "N:\map\new.xlsx")
                    sheets = wb.sheetnames
                    Sheet1 = wb[sheets[0]]
                    print Sheet1
                    Sheet1.range(2, 4).value = utkategoria  # This will change the cell(2,4) to 4
                    wb.save("N:\map\new_v2.xlsx")

Solution

  • dir(Sheet1) does not show range as an option. To edit the value of the cell (2,4), please use

    Sheet1.cell(row=2,column=4).value = utkategoria