简体   繁体   English

循环遍历 excel 工作表并使用 Python 将值存储在变量中

[英]Iterate with loop through excel sheet and store values in variables using Python

I was trying to read dats from excel sheet using python, due to some constraints i'm not able to use external libraries.我试图使用 python 从 excel 表中读取数据,由于某些限制,我无法使用外部库。 I'm doing it with from Microsoft.Office.Interop import Excel.我是从 Microsoft.Office.Interop 导入 Excel 来做的。 Now I'm able to read the datas from sheet by defining them explicitly.现在我可以通过明确定义它们来读取工作表中的数据。 like,喜欢,

x1=ws.Rows[3].Value2[0,0]
y1=ws.Rows[3].Value2[0,1]
z1=ws.Rows[3].value2[0,2]

x2=ws.Rows[4].value2[0,0]
y2=ws.Rows[4].value2[0,1]
z2=ws.Rows[4].value2[0,2]

x3=ws.Rows[5].value2[0,0]
y3=ws.Rows[5].value2[0,1]
z3=ws.Rows[5].value2[0,2]

x4=ws.Rows[6].value2[0,0]
y4=ws.Rows[6].value2[0,1]
z4=ws.Rows[6].value2[0,2]

But I want to loop it.但我想循环它。 How to loop it?如何循环它? at the end i need values in variables.最后我需要变量中的值。

Assuming that you are reading a fixed number of 3 values for each row, I would recommend to use 3 lists for x, y, and z as a data structure:假设您正在为每行读取固定数量的 3 个值,我建议使用 x、y 和 z 的 3 个列表作为数据结构:

x = []
y = []
z = []
for row in ws.Rows[3:]:
    x.append(row.Value2[0,0])
    y.append(row.Value2[0,1])
    z.append(row.Value2[0,2])

Then you can access your values via x[0] , z[4] etc.然后您可以通过x[0]z[4]等访问您的值。

If the number of columns is also variable, you should use a 2D array and two nested for loops for assigning the values.如果列数也是可变的,则应使用2D 数组和两个嵌套的 for 循环来分配值。

If you really want to declare the variables in the described way you could use, here you will get the 5 first x,y,z positions from your excel:如果您真的想以您可以使用的描述方式声明变量,在这里您将从 excel 中获得前 5 个 x、y、z 位置:

for i in range(5):
    globals()['x{0}'.format(i)] = ws.Rows[i + 2].Value2[0,0]
    globals()['y{0}'.format(i)] = ws.Rows[i + 2].Value2[0,1]
    globals()['z{0}'.format(i)] = ws.Rows[i + 2].Value2[0,2]

I however would recommend storing the points in a list of dictionary like this:但是,我建议将这些点存储在这样的字典列表中:

positions = list()
for i in range(5):
    positions.append({
        'x': ws.Rows[i + 2].Value2[0,0]
        'y': ws.Rows[i + 2].Value2[0,1]
        'z': ws.Rows[i + 2].Value2[0,2]
    })
led = []
for i in range(5):
    globals()['x' + 'i'] = ws.Rows[i + 2].Value2[0,0]
    globals()['y' + 'i'] = ws.Rows[i + 2].Value2[0,1]
    globals()['z' + 'i'] = ws.Rows[i + 2].Value2[0,2]
    led.append(globals()['x' + 'i'])
    led.append(globals()['y' + 'i'])
    led.append(globals()['z' + 'i'])

It worked for me,as per my requirements.根据我的要求,它对我有用。

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

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