openpyxl将数据类型列表转化为单行多列

问题描述 投票:0回答:1

如果我的格式不好,我很抱歉我不经常使用堆栈溢出。

我的问题是我有一个列表,我想将数据附加到 Excel 工作表中,每次运行脚本时我希望它将数据添加到下一行并填充该行中的列单元格,因此水平添加数据但是,当使用下面的代码部分时,该表会将每个索引添加为新行,并且垂直堆叠数据。我尝试过嵌套 for 循环,但由于我是初学者,可能是由于我的实现不佳,这让事情变得混乱。

每次运行脚本时,列表的结构看起来都是这样的:

stats = [[25.564994], [36.41515], [14.5465], [15.1859541], ['example'], ['example']]

我希望如何使用上述列表 stats[] 结构来格式化数据:

再次运行脚本并获取另一轮数据 ID,以便在下一行中记录该数据。

file_path = 'filename'
wb = load_workbook(file_path)
sheet = wb.active
for data in stats:
    sheet.append(data)
wb.save(filename='filename')

我厌倦了像我之前所说的那样使用嵌套 for 循环,但我似乎把事情弄得一团糟,所以我回到了代码块中的原始结构,但是,我现在有点卡住了,不知道该尝试什么。

python openpyxl
1个回答
0
投票
import openpyxl
import os

stats = [[25.564994], [36.41515], [14.5465], [15.1859541], ['example'], ['example']]


filename = 'whatever_name_it_is.xlsx'

if not os.path.exists(filename):   #this line is checking weather the file name already exist or not if not then it will create a new file of the previously specified name
    book = openpyxl.Workbook()
    book.save(filename)
else:
    book = openpyxl.load_workbook(filename) #like i said if the file name already exist it will open that file

#now it will look for the sheet name in the file ( in this case "sheet_1") if sheet_1 exist it will  use it, otherwise it will create a new one
sheet1 = book.get_sheet_by_name("sheet_1") if "sheet_1" in book.sheetnames else book.create_sheet("sheet_1") 

# in the following line it will the stats value in the sheet from row 3 and coloumn 2  onwards, starting with B3
for i in range(len(stats)):
    sheet1.cell(row=3, column=i+2, value=stats[i][0]) #after each iteration it will  go to the next row with the i value incrementing each time

#finally it will save the file
book.save(filename)

# and a confirmation message just to confirm
print("Operation Successful \n Check the excel file in the current working directory")

我使用了 for 循环来迭代列表的长度。每次迭代时,工作表的列编号值都会增加,以将下一个元素保存在后续列中,水平前进。最初的“if”语句验证文件名是否已存在。为了清楚起见,我在评论中提供了解释。

© www.soinside.com 2019 - 2024. All rights reserved.