openpyxl - 只写工作表无法添加表

时间:2017-08-23 18:35:18

标签: python excel openpyxl

我想写一个新的工作簿,有一张表,并在该表中添加一个表。 AFAIK应该是可能的,这个提交应该做https://bitbucket.org/openpyxl/openpyxl/commits/6f440b0ed398

但是当我尝试这样做时,它失败并显示消息:

KeyError: 'Unknown relationship: None'

我的代码段是:

from openpyxl import Workbook
from openpyxl.worksheet.table import Table

wb = Workbook(write_only=True)
ws = wb.create_sheet()

ws.append(['col1','col2','col3','col4'])
ws.append(['val11','val12','val13','val14'])
ws.append(['val21','val22','val23','val24'])
ws.append(['val31','val32','val33','val34'])
ws.append(['val41','val42','val43','val44'])

table = Table(displayName="basetable", ref="A1:D4")
ws.add_table(table)
wb.save('table.xlsx')

完整的追溯是:

File "<stdin>", line 1, in <module>
    wb.save('table.xlsx')

File "./site-packages/openpyxl/workbook/workbook.py", line 354, in save
    save_dump(self, filename)

File "./site-packages/openpyxl/writer/excel.py", line 313, in save_dump
    writer.save(filename)

File "./site-packages/openpyxl/writer/excel.py", line 266, in save
    self.write_data()

File "./site-packages/openpyxl/writer/excel.py", line 83, in write_data
    self._write_worksheets()

File "./site-packages/openpyxl/writer/excel.py", line 229, in _write_worksheets
    ws._rels[t._rel_id].Target = t.path

File "./site-packages/openpyxl/packaging/relationship.py", line 97, in __getitem__    
    raise KeyError("Unknown relationship: {0}".format(key))

1 个答案:

答案 0 :(得分:-2)

  

问题:只写工作表无法添加表格

试过你的例子了:

AttributeError: 'WriteOnlyWorksheet' object has no attribute 'add_table'

已移除write_only=True,工作正常。

  

<强>输出
  enter image description here

使用Python测试:3.4.2和2.7.9 - openpyxl:2.4.1 - LibreOffice:4.3.3.2