能否用python-docx在特定位置插入行?

10 人关注

我想用 python-docx 在表的中间插入几行。有什么方法可以做到这一点吗?我已经尝试用一个 类似于插入图片的方法 but it didn't work.

如果没有,我希望得到任何关于哪个模块更适合这项任务的提示。谢谢。

这是我试图模仿插入图片的想法。这是不对的。'Run'对象没有'add_row'属性。

from docx import Document
doc = Document('your docx file')
tables = doc.tables
p = tables[1].rows[4].cells[0].add_paragraph()
r = p.add_run()
r.add_row()
doc.save('test.docx')
    
2 个评论
Show code 哪些事情没有成功。
T0f
@dotancohen 结果发现'Run'对象没有'add_row'属性。我已经在问题中加入了代码,但这显然是错误的方法。
python
python-docx
T0f
T0f
发布于 2017-09-14
6 个回答
scanny
scanny
发布于 2022-03-03
已采纳
0 人赞同

简短的回答是:没有。API中没有 Table.insert_row() 方法。

一个可能的方法是编写一个所谓的 "工作函数",直接操作底层的XML。你可以从任何给定的XML元素(例如本例中的 <w:tbl> 或也许是 <w:tr> )的 python-docx 中获取。 proxy 对象。比如说。

tbl = table._tbl

这给了你一个XML层次结构的起点。从那里你可以从头开始创建一个新的元素,或者通过复制和使用lxml._Element来创建一个新的元素。API调用将其放置在XML中的正确位置。

这是一个有点高级的方法,但可能是最简单的选择。据我所知,目前没有其他的Python软件包提供更广泛的API。另一个选择是在Windows中用他们的COM API或其他VBA做一些事情,可能是IronPython。这只能在运行Windows操作系统的小规模(桌面,而不是服务器)中工作。

python-docx workaround functionpython-pptx workaround function上搜索会发现一些例子。

T0f
非常感谢您的详细解释!
Иван Ежов
Иван Ежов
发布于 2022-03-03
0 人赞同

你可以插入行到表的末尾,然后在另一个位置移动它,方法如下。

from docx import Document
doc = Document('your docx file')
t = doc.tables[0]
row0 = t.rows[0] # for example
row1 = t.rows[-1]
row0._tr.addnext(row1._tr)
    
allen alex
allen alex
发布于 2022-03-03
0 人赞同

虽然根据 python-docx 文档,没有一个直接可用的 api 来实现这一点,但是有一个简单的解决方案,不需要使用任何其他的 lib,比如 lxml,只需要使用 python-docx 提供的底层数据结构,也就是 CT_Tbl, CT_Row 等。 这些类确实有常见的方法,比如addnext, addprevious,可以方便地在当前元素的后面/前面添加元素作为兄弟姐妹。 所以这个问题可以按以下方式解决,(在 python-docx v0.8.10 上测试)

from docx import Document doc = Document('your docx file') tables = doc.tables row = tables[1].rows[4] tr = row._tr # this is a CT_Row element for new_tr in build_rows(): # build_rows should return list/iterator of CT_Row instance tr.addnext(new_tr) doc.save('test.docx')

this should solve the problem

Denis Cottin
Denis Cottin
发布于 2022-03-03
0 人赞同

你可以通过这种方式在最后一个位置添加一行。

from win32com import client
doc = word.Documents.Open(r'yourFile.docx'))
doc = word.ActiveDocument
table = doc.Tables(1)  #number of the tab you want to manipulate
table.Rows.Add()
    
Gowtham K
Gowtham K
发布于 2022-03-03
0 人赞同

中的addnext()。 lxml.etree 这似乎是一个更好的选择,它工作得很好,唯一的问题是,我不能设置行的高度,所以请提供一些答案,如果你知道的话!

current_row = table.rows[row_index] 
table.rows[row_index].height_rule = WD_ROW_HEIGHT_RULE.AUTO
tbl = table._tbl
border_copied = copy.deepcopy(current_row._tr)
tr = border_copied
current_row._tr.addnext(tr)
    
Average Godot Enjoyer
Average Godot Enjoyer
发布于 2022-03-03
0 人赞同

我在这里创建了一个视频来演示如何做到这一点,因为它第一次把我吓了一跳。 https://www.youtube.com/watch?v=nhReq_0qqVM

    document=Document("MyDocument.docx")
    Table = document.table[0]
    Table.add_row()
    for cells in Table.rows[-1].cells:
         cells.text = "test text"
    insertion_row = Table.rows[4]._tr
    insertion_row.add_next(Table.rows[-1]._tr)