【问题标题】:How to add table border to word doc using python docx如何使用python docx将表格边框添加到word doc
【发布时间】:2017-04-23 04:39:34
【问题描述】:

我正在尝试使用 Python 的 docx 模块创建一个 word 文档。 但是我无法为其添加表格边框。

我的代码如下:

    import docx
    from docx import Document
    from docx.shared import Pt
    doc = Document('C:/Users/Vinny/Desktop/Python/Template.docx')
    doc.add_paragraph('Changes:')

    doc.add_paragraph('Metrics:')
    #add table
    table = doc.add_table(rows = 4, cols = 2, style='TableGrid')
    doc.save('C:/Users/Vinny/Desktop/Python/rel.docx')

但它会抛出错误:

Traceback (most recent call last):
  File "C:\Users\Vinny\Desktop\Python\abc.py", line 14, in <module>
    table = doc.add_table(rows = 4, cols = 2, style='TableGrid')
  File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\document.py", line 100, in add_table
    table.style = style
  File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\table.py", line 134, in style
    style_or_name, WD_STYLE_TYPE.TABLE
  File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\parts\document.py", line 76, in get_style_id
    return self.styles.get_style_id(style_or_name, style_type)
  File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py", line 113, in get_style_id
    return self._get_style_id_from_name(style_or_name, style_type)
  File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py", line 143, in _get_style_id_from_name
    return self._get_style_id_from_style(self[style_name], style_type)
  File "C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py", line 57, in __getitem__
    raise KeyError("no style with name '%s'" % key)
KeyError: "no style with name 'TableGrid'"

谁能帮我解决这个问题?

【问题讨论】:

  • 确保您阅读了文档中的这一页以及紧随其后的那一页(使用“下一步”按钮):python-docx.readthedocs.io/en/latest/user/…
  • 它工作正常并创建了所需的文档。我在模板中添加了表格网格,删除并保存了它。工作正常。唯一的事情是每次都显示一条警告消息。警告消息类似于:“文件“C:\Users\Vinny\AppData\Local\Programs\Python\Python36-32\lib\site-packages\docx\styles\styles.py”,第 54 行警告(msg,UserWarning)用户警告:不推荐使用 style_id 查找样式。请改用样式名称作为键。s : "
  • 堆栈跟踪的其余部分是什么?
  • @VinnyKaur 检查此链接以修复您的警告stackoverflow.com/questions/28973277/…
  • 啊!我检查了一下,它起作用了,谢谢@MarutiMohanty。

标签: python python-3.x docx python-docx


【解决方案1】:

试试空格:

table = doc.add_table(rows = 4, cols = 2, style='Table Grid')

我遇到了同样的问题,这对我有用。

【讨论】:

    【解决方案2】:
    from docx.enum.style import WD_STYLE_TYPE
    

    还要加空格来制作style='Table Grid'

    【讨论】:

    • @AhmedMamdouh 您认为它不起作用有什么原因吗?它肯定对我有用,也适用于其他一些回答过这个问题的人。
    【解决方案3】:

    使用空间:

    table = document.add_table(rows=1, cols=3, style='Table Grid')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      相关资源
      最近更新 更多