输出到新工作表的n行和特定列的xlwings语法

时间:2015-02-11 18:44:32

标签: python excel xlwings

我一直在尝试为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

2 个答案:

答案 0 :(得分:1)

xlwings是excel的一个非常酷的界面 - Range对象将为您的应用程序做繁重的工作。根据您的列是否全部包含在内,您可以使用tablevertical方法一起读取或逐列读取。以下是Excel中一组简单数据的两种等效方法:

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

python代码是:

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] 

在任何一种情况下,第二和第四个数据点都将写在与Sheet 1相同的行上的Sheet 2

答案 1 :(得分:-1)

xlwingsPython编程语言的包。要学习Python,您可以在官方网站上开始,例如:https://www.python.org/about/gettingstarted/