python上下对齐,python docx在同一行上左右对齐

This is my first question on SO and would like to thank you all in advance for any help. I'm pretty new to python, python-docx and programming in general. I am working on a GUI program (using PyQt) to generate a contract in docx format. I have most things working, but here is the problem I am having. I need to align text both left and right on the same line. In word, I believe this is done by changing to a right indent and hitting tab, then adding the text. However, I cannot figure out how to do this in python-docx. I tried:

paragraph = document.add_paragraph()

paragraph.add_run('SOME TEXT')

paragraph.alignment = 0

paragraph.add_run('SOME OTHER TEXT')

paragraph.alignment = 2

but this didn't work. I tried some other ideas per the documentation, like enum WD_PARAGRAPH_ALIGNMENT, but nothing worked.

Is this possible to do in python-docx (im using version 0.8.5)?

Thanks for any help!

解决方案

Not sure if you're still looking for a solution, but...

I am also generating contracts with python-docx and came across this same issue. Until the right-aligned tab stop feature is added, my workaround is to format the line as a table, using a custom table style.

First, open a document ('custom_styles.docx') and add a table with 1 row and 2 columns.

Select the table and add a new table style ('CustomTable'), where the first column is left-aligned and the last column is right-aligned. (I also made the borders invisible by setting them to 'none' or coloring them white.)

Delete the table and save the document, which will give you an empty document with the new 'CustomTable' style.

The following should work for creating a line that appears to be both left-aligned and right-aligned:

from docx import Document

document = Document('custom_styles.docx')

table = document.add_table(1, 2, style='CustomTable')

table.cell(0,0).text = 'Left Text'

table.cell(0,1).text = 'Right Text'

document.save('new_document_name.docx')

The trickiest part for me was figuring out how to create the table style in Word.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值