代码之家  ›  专栏  ›  技术社区  ›  T0f

是否可以使用python docx在特定位置插入行?

  •  10
  • T0f  · 技术社区  · 7 年前

    我想使用 python-docx similar to inserting pictures approach 但它不起作用。

    这是我试图模仿插入图片的想法。这是不对的。”运行“object”没有属性“add\u 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')
    
    6 回复  |  直到 3 年前
        1
  •  5
  •   scanny    7 年前

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

    一种可能的方法是编写一个所谓的“变通函数”,直接处理底层XML。您可以访问任何给定的XML元素(例如。 <w:tbl> <w:tr> )从它的 python-docx

    tbl = table._tbl
    

    lxml._Element API调用将其放置在XML中的正确位置。

    这是一种有点高级的方法,但可能是最简单的选择。据我所知,没有其他Python包提供更广泛的API。另一种选择是在Windows中使用COM API或VBA中的任何东西,可能是IronPython。这只适用于运行Windows操作系统的小规模(桌面,而不是服务器)。

    搜索 python-docx workaround function python-pptx workaround function 我会给你找一些例子。

        2
  •  3
  •   Иван Ежов    5 年前

    您可以将行插入表的末尾,然后将其移动到另一个位置,如下所示:

    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)
    
        3
  •  2
  •   allen alex    5 年前

    虽然根据python docx文档,没有直接可用的api来实现这一点,但有一个简单的解决方案,不使用任何其他LIB(如lxml),只使用python docx提供的底层数据结构,即CT\U Tbl、CT\U 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')
    
    

    这应该可以解决问题

        4
  •  1
  •   Denis Cottin    6 年前

    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()
    
        5
  •  1
  •   Gowtham K    5 年前

    中的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)
    
        6
  •  1
  •   Average Godot Enjoyer    2 年前

    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)
        
        document.save("MyDocument.docx")
    

    python docx模块没有用于此的方法,因此我找到的最佳解决方法是在表的底部创建一个新行,然后使用xml元素中的方法将其放置在假设的位置。