简体   繁体   English

希望使用 openpyxl 将数据添加到命名的 excel 表中

[英]Looking to add data to a named excel table using openpyxl

I am trying to add data to a named table in excel, but I don't know how to add additional rows to a named excel table as the openpyxl documentation is not helpful on what this package does.我正在尝试将数据添加到 excel 中的命名表中,但我不知道如何向命名的 excel 表中添加额外的行,因为 openpyxl 文档对这个包的作用没有帮助。 The best I have been able to do so far, which has not worked, is the following:到目前为止,我能做的最好的事情如下:

test = load_workbook(r'\\data4\users2\wyoung3\My Documents\Test.xlsx')
twb = test['Sheet2']
twbs = twb._tables
twbs = twbs.append(['s']) #this was my attempt to try and append an item to the bottom of the list
test.save(r'\\data4\users2\wyoung3\My Documents\Test.xlsx')

This resulted in a file that I could not open and the error message:这导致我无法打开一个文件和错误消息:

AttributeError: 'list' object has no attribute 'tableColumns' AttributeError: 'list' 对象没有属性 'tableColumns'

Can anyone advise on how I can go about addressing this problem?任何人都可以就我如何解决这个问题提出建议吗?

The question you are asking is not very clear, so I will provide a few options.你问的问题不是很清楚,所以我提供几个选项。 The tutorial for openpyxl is actually decent, so you should try going through it. openpyxl教程实际上很不错,所以你应该尝试openpyxl它。

First, usingTables :首先,使用表格

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

wb = Workbook()
ws = wb.active

data = [
    ['Apples', 10000, 5000, 8000, 6000],
    ['Pears',   2000, 3000, 4000, 5000],
    ['Bananas', 6000, 6000, 6500, 6000],
    ['Oranges',  500,  300,  200,  700],
]

# add column headings. NB. these must be strings
ws.append(["Fruit", "2011", "2012", "2013", "2014"])
for row in data:
    ws.append(row)

tab = Table(displayName="Table1", ref="A1:E5")

# Add a default style with striped rows and banded columns
style = TableStyleInfo(name="TableStyleMedium9", showFirstColumn=False,
                       showLastColumn=False, showRowStripes=True, showColumnStripes=True)
tab.tableStyleInfo = style
ws.add_table(tab)
wb.save("table.xlsx")

Alternatively, if you know the cell location already, you can simply insert_rows() .或者,如果您已经知道单元格位置,则只需insert_rows()

The default is one row or column.默认为一行或一列。 For example to insert a row at 7 (before the existing row 7):例如在第 7 行(在现有第 7 行之前)插入一行:

ws.insert_rows(7)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM