I'm trying to use python to migrate some data. I need to test see if I have specific column, then if cell value is one value, change to specific other value. So my problem is, how to do test for coordinate.
I am using python and excel. I need to read in excel file, then make changes to data, and output new, changed excel file. I'm using Python and PyCharm and now trying with openpyxl. I tried xlrd/xlwt, and tried doing with csv. To take data from sql to excel file, then make changes - this seemed to be easiest way to do.
So for instance, in specific case, I have in column 4 field for sex. So I try to specify only column 4 then. Old data has values either "Male" or "Female" new data needs to be numeric code, 1 for Male and 2 for Female.
for cellObj in row:
if cellObj.coordinate == [4:row]:
if cellObj.value == 'Male':
cellObj.value = 1
elif cellObj.value == 'Female':
cellObj.value = 2
(Sorry, I try to make format for question right, but code doesn't show the same.)
This code is not right. I don't understand how to do this. I have book Automate The Boring Stuff With Python by Al Sweigart. I have been looking in forums and blogs, but always you must know the exact coordinates. That's why I try with specific column 4 rather than testing in code to see which column I need.
EDIT:
I could not add to commant. Here is all code. Only getting 1 row now.
wb = openpyxl.load_workbook(file_location)
sheet = wb.worksheets[0]
for cellObj in sheet.rows[0]:
print(cellObj.value),
print(' | '),
for row in sheet.iter_rows():
for row_count, cellObj in enumerate(row):
if cellObj.coordinate == 'E{}'.format(row_count):
print row_count
print(cellObj.value),
if cellObj.value == 'Male':
cellObj.value = 1
print(cellObj.value)
elif cellObj.value == 'Female':
cellObj.value = 2
print(cellObj.value)
I added and change sheet.iter_rows....This here: OpenPyXL + How can I search for content in a cell in Excel, and if the content matches the search criteria update the content? But this doesn't work either. On for loop, I can't do:
for i in sheet:
do this for each row "i"
This format does not work?
Also, here: OpenPyXL + How can I search for content in a cell in Excel, and if the content matches the search criteria update the content? Someone said can do sheet.rows() to go through each row, but this gives the tuple error again. TypeError: 'tuple' object is not callable