0

我一直在尝试为 xlwings 所需的语法寻找一个好的资源,但没有成功。我正在尝试制作一个程序,该程序将重复 n 行数据并将某些信息输出到新工作表。这是算法的一个片段。如果你能给我指一个好的参考或只是伸出援助之手,我将不胜感激。

data = number of rows in worksheet #either input the number manually or automate 

for row n to data: #start at row 1 and loop through each line of data

    axles = get row n, column M data #retrieve data in column M 
    if axles<2: #Test the data from column M for validity 
        continue #return to the for loop and start on next line

    distance = get row n, column Q data #retrieve data in column Q 
    if distance < 100 or distance > 300: #test the data from column Q for validity
        continue #return to the for loop and start on next line

    weight = get row n, column P data #retrieve data in column P 
    print weight into row n, column A on sheet 2 #display output on a new sheet
4

2 回答 2

1

xlwings 是一个非常酷的 excel 界面 - 该Range对象将为您的应用程序完成繁重的工作。根据您的列是否都在一起,您可以使用tableorvertical方法一起阅读或逐列阅读。以下是 Excel 中一组简单数据的两种等效方法:

axles   distance    weight
1       150         1.5
2       200         2
1       250         2.5
2       300         3
4       350         3.5

蟒蛇代码是:

from xlwings import Workbook, Range

wb=Workbook(r'C:\\Full\\Path\\to\\Book1.xlsx')

# Method 1:
# if your table is all together read it in at once:
# read all data in as table
allrows=Range('Sheet1','A2').table.value 
for rownum, row in enumerate(allrows):
    axles=row[0]
    if axles<2:
        continue
    distance=row[1]
    if distance< 100 or distance>300:
        continue
    weight = row[2]
    # +2 to correct for python indexing and header row
    Range('Sheet2',(rownum+2,1)).value=weight 

# Method 2:
# if your columns are separated read them individually:
# read all data in as columns
axles=Range('Sheet1','A2').vertical.value 
distance=Range('Sheet1','B2').vertical.value
weight=Range('Sheet1','C2').vertical.value
# in case the columns have different lengths, look at the shortest one
for rownum in range(min(len(axles),len(distance),len(weight))):
    if axles[rownum]<2:
        continue
    if distance[rownum]< 100 or distance[rownum]>300:
        continue
    # +2 to correct for python indexing and header row
    Range('Sheet2',(rownum+2,1)).value=weight[rownum] 

在任何一种情况下,第二个和第四个数据点都将写入工作表 2 中与工作表 1 相同的行

于 2015-04-04T16:00:52.043 回答
-1

xlwingsPython编程语言的一个包。学习Python,可以从官网开始,例如:https ://www.python.org/about/gettingstarted/

于 2015-02-12T10:46:40.717 回答