如何将多个 excel 行放入一个包含子列表的大列表中?
How do I put multiple excel rows into one big list with sublists?
如何将多个 excel 行放入一个大列表中,每个 excel 行都有子列表?我使用 openpyxl 从 .xlsx 文件中提取数据,然后使用 .iter_rows 获取所有需要的行值,如下所示:
from openpyxl import load_workbook
workbook = load_workbook(filename=r"C:\Users\file.xlsx")
sheet = workbook.active
for row in sheet.iter_rows(min_row=2,
max_row=21,
min_col=1,
max_col=4,
values_only=True):
print(row)
listtest = []
for cell in row:
listtest.append(cell)
print(listtest)
我试过使用这种方法,但它只将最后一行放入列表中,得到如下输出:
(1, 1, 12, 4)
(2, 1, 8, 3)
...
...
(20, 101, 3, 11)
[20, 101, 3, 11]
我正在尝试获得这样的输出:
[['1', '1', '12', '4'], ['2', '1', '8', '3'], ... , ['20', '101', '3', '11']]
如果有人能在这里让我朝着正确的方向前进,我会很高兴的:)
谢谢
您可以使用 pandas:
import pandas as pd
df = pd.read_excel(r"C:\Users\file.xlsx")
list_of_lists = df.applymap(str).to_numpy().tolist()
这应该 return 您正在寻找的东西。
那是因为您在循环的每次迭代中都覆盖了 listtest
。要坚持您的原始代码(稍作修改),请尝试:
output = []
for row in sheet.iter_rows(min_row=2,
max_row=21,
min_col=1,
max_col=4,
values_only=True):
listtest = []
for cell in row:
listtest.append(cell)
output.append(listtest)
如何将多个 excel 行放入一个大列表中,每个 excel 行都有子列表?我使用 openpyxl 从 .xlsx 文件中提取数据,然后使用 .iter_rows 获取所有需要的行值,如下所示:
from openpyxl import load_workbook
workbook = load_workbook(filename=r"C:\Users\file.xlsx")
sheet = workbook.active
for row in sheet.iter_rows(min_row=2,
max_row=21,
min_col=1,
max_col=4,
values_only=True):
print(row)
listtest = []
for cell in row:
listtest.append(cell)
print(listtest)
我试过使用这种方法,但它只将最后一行放入列表中,得到如下输出:
(1, 1, 12, 4)
(2, 1, 8, 3)
...
...
(20, 101, 3, 11)
[20, 101, 3, 11]
我正在尝试获得这样的输出:
[['1', '1', '12', '4'], ['2', '1', '8', '3'], ... , ['20', '101', '3', '11']]
如果有人能在这里让我朝着正确的方向前进,我会很高兴的:) 谢谢
您可以使用 pandas:
import pandas as pd
df = pd.read_excel(r"C:\Users\file.xlsx")
list_of_lists = df.applymap(str).to_numpy().tolist()
这应该 return 您正在寻找的东西。
那是因为您在循环的每次迭代中都覆盖了 listtest
。要坚持您的原始代码(稍作修改),请尝试:
output = []
for row in sheet.iter_rows(min_row=2,
max_row=21,
min_col=1,
max_col=4,
values_only=True):
listtest = []
for cell in row:
listtest.append(cell)
output.append(listtest)