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

2024-10-04 01:35:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图向excel中的命名表中添加数据,但我不知道如何向命名excel表中添加其他行,因为openpyxl文档对这个包的功能没有帮助。到目前为止,我所能做的最好的事情是以下几点,但这些都没有奏效:

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')

这导致我无法打开一个文件,并显示错误消息:

AttributeError: 'list' object has no attribute 'tableColumns'

有人能建议我如何着手解决这个问题吗


Tags: thetotestmyxlsxexcel命名documents
1条回答
网友
1楼 · 发布于 2024-10-04 01:35:23

你问的问题不是很清楚,所以我会提供一些选择。用于openpyxltutorial实际上是相当不错的,因此您应该尝试使用它

首先,使用Tables

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")

或者,如果您已经知道单元格位置,您可以简单地insert_rows()

The default is one row or column. For example to insert a row at 7 (before the existing row 7):

ws.insert_rows(7)

相关问题 更多 >