1

I want to write a python script which should read xlsx file and based on value of column X, it should write/append file with the value of column Z.

Sample data:

Column A    Column X    Column Y    Column Z
123     abc     test        value 1
124     xyz     test        value 2
125     xyz     test        value 3
126     abc     test        value 4

If value in Column X = abc then it should create a file (if not existing already) in some path with name abc.txt and insert the value of column Z in abc.txt file, likewise if Column X = xyz then it should create a file in same path with xyz.txt and insert the value of column Z in xyz.txt file.

from openpyxl import load_workbook
wb = load_workbook('filename.xlsm')
ws = wb.active
for cell in ws.columns[9]:  #here column 9 is value is what i am testing which is Column X of my example.
    if cell.value == "abc":
        print ws.cell(column=12).value  #this is not working and i dont know how to read corresponding value of another column

Please suggest what could be done.

Thank you.

1 Answer 1

1

Change

print ws.cell(column=12).value

By:

print ws.columns[col][row].value

in your case:

print ws.columns[12-1][cell.row-1].value

Note that if you use this indexation method cols and rows start with index 0. This is why I'm doing cell.row-1, so take it into account when you address your column, if your 12 starts counting from 1 you'll have to address to 11.

Alternatively you can access to your information cell like this: ws.cell(row = cell.row, column = 12).value. Note in this case cols and rows start at 1.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.