Fabricio G
Fabricio G

Reputation: 111

error when trying to concatenate data from a xlsx sheet with a string

let's begin with my code, then I'll explain my issue

for row in ws.iter_rows(min_row =1, max_col=2):
    for cell in row:
        a.write('a string"' + a.write(str(cell.value)))

i know for a fact that the data i'll be reading is an integer, so that's why I believe this piece of code is getting the error bellow

TypeError: can only concatenate str (not "int") to str

But I want python to read the data on the xlsx as a string, even tough they are just numbers, how can I do that?

Upvotes: 0

Views: 122

Answers (1)

nonethewiser
nonethewiser

Reputation: 608

Try this:

for row in ws.iter_rows(min_row =1, max_col=2):
    for cell in row:
        a.write('a string"' + str(cell.value))

I think you just need to remove the nested a.write(). You have the right idea in casting it to a str if you want to concatenate it.

If you're using python 3.6 you can use f-strings instead:

for row in ws.iter_rows(min_row =1, max_col=2):
    for cell in row:
        a.write(f'a string"{cell.value}'))

Note, if cell.value is 1, this will result in a string"1. This is how you've written it although it might be a typo.

Upvotes: 1

Related Questions