0

Attempting to format output to a LibreOffice calc (ie, linux-based Excel) document but the python format syntax isn't applied as expected.

Using the new string formatting, running the below:

import openpyxl as xl
wb = xl.Workbook()
ws = wb.active

ws['A3'] = '{:>}'.format('rundate:')
ws['A4'] = '{:>}'.format('name:')
ws['A5'] = '{:>}'.format('comments:')

wb.save('test.xlsx')

Unexpectedly gives this, which appears to be left rather than right aligned:

enter image description here

Trying the left align char on the off chance I had them reversed:

import openpyxl as xl
wb = xl.Workbook()
ws = wb.active

ws['A3'] = '{:<}'.format('rundate:')
ws['A4'] = '{:<}'.format('name:')
ws['A5'] = '{:<}'.format('comments:')

wb.save('test.xlsx')

Returns the same:

enter image description here

And another version (specifying total number of chars), makes it clear the text isn't being right aligned. If anything, right aligned text should spill over the left side of the cell, not the right.

import openpyxl as xl
wb = xl.Workbook()
ws = wb.active

ws['A3'] = '{:>12}'.format('rundate:')
ws['A4'] = '{:>12}'.format('name:')
ws['A5'] = '{:>12}'.format('comments:')

wb.save('test.xlsx')

enter image description here

1
  • To the downvoter, what was the issue? Commented Feb 3, 2020 at 11:01

1 Answer 1

1

From the alignment module:

Alignment options for use in styles.

horizontal Value must be one of {‘left’, ‘centerContinuous’, ‘center’, ‘distributed’, ‘fill’, ‘justify’, ‘right’, ‘general’}

I think this will work:

from openpyxl.styles import Alignment
alignment=Alignment(horizontal='left')

import openpyxl as xl
wb = xl.Workbook()
ws = wb.active

for row in ws.iter_rows(min_col=1, max_col=1, min_row=3, max_row=5):
    for cell in row:
        cell.alignment = alignment

wb.save('test.xlsx')

or simply:

ws['A3'].alignment = Alignment(horizontal='left')
ws['A4'].alignment = Alignment(horizontal='left')
ws['A5'].alignment = Alignment(horizontal='left')
Sign up to request clarification or add additional context in comments.

1 Comment

Ugh, so janky...already needed two other sets of loops to format cells, this would be a cherry on top. Try in a few, thanks.

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.