gpt4 book ai didi

python - openpyxl 追加到右侧

转载 作者:行者123 更新时间:2023-12-01 09:01:26 31 4
gpt4 key购买 nike

我对 openpyxl 还很陌生,遇到了一些问题

我正在循环访问一个列表,并为每个项目添加一个标题和一些数据。我的问题是,对于我遇到的每个项目,我想在右侧添加“相同”数据,而不是像 .append 方法那样从上到下。

不知道有没有道理。

一个例子

for agreement in agreements:
n1 = wb.active

n1.append([
make_cell(n1, agreement.name, bold=True),
])

n1.append([
'Account Number',
'Account Name',
'Total DKK',
])

for ....
n1.append(....)

对于每个协议(protocol),我想在右侧添加“相同”数据,而不是颠倒。

如何做到这一点?

我想要什么..

headline                headline                headline        
Account Number Account Name Total DKK Account Number Account Name Total DKK Account Number Account Name Total DKK

最佳答案

Question: ... add the "same" data to the right, not top down like the .append method

您必须使用ws.append(...)反正。

首先你需要一个Workbook实例:

from openpyxl import Workbook
wb = Workbook()

Don't use n1 = wb.active inside your for ... loop.
You have to get the active Worksheet only once.

for agreement in agreements:
n1 = wb.active
ws = wb.active

You want to add x Header per Row to the right, so you can't use .append(...).

    n1.append(['Account Number', 'Account Name', 'Total DKK',])

在你之前.append(...)您的行列值,您必须创建一个包含您预期值的列表。
例如:

HEADER = ['Account Number', 'Account Name','Total DKK']    
listOfColumnValues = []

# Extend listOfColumnValues with HEADER as many times you need
for _ in range(3):
listOfColumnValues.extend(HEADER)

print("{}".format(listOfColumnValues))
ws.append(listOfColumnValues)

Output:

['Account Number', 'Account Name', 'Total DKK', 'Account Number', 'Account Name', 'Total DKK', 'Account Number', 'Account Name', 'Total DKK']

使用 Python:3.4.2 - openpyxl:2.4.1 - LibreOffice:4.3.3.2 进行测试

关于python - openpyxl 追加到右侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52426831/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com