Python Forum

Full Version: openpyxl and newline characters
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Why won't openpyxl accept newline characters??

Yesterday I wanted to put some questions in an excel file. The questions are in a text file, each on a separate line.

Qs = open(questions)
Qs_data = Qs.readlines()
Got the questions, now I want to put them in the wb. In the Python shell I saw the output from Python writing to the cells concerned.

When I saved and opened the workbook: No questions, but Python showed no error!

Took me a while to realize that the newline characters were causing the problem. I put Q = thisQ.strip(), then it worked.

#put the questions in the wb column 1
    # they are long
    # start in row 3, increment by 5 each time
    count = 3
    # num is for the question numbers here
    num = 1
    for q in Qs_data:
        thisQ = 'Q'+str(num) + ': ' + q
        # for some reason openpyxl won't accept \n
        # no error, but nothing gets written, so need to strip away the \n
        Q = thisQ.strip()
        print(thisQ)
        wb[this_survey].cell(row=count, column=1, value=Q)
        # this is for the percent values
        wb[this_survey].cell(row=count+75, column=1, value=Q)
        count+=5
        num+=1