python3 利用xlrd,xlwt编写一个简单的数据分析程序

python3 利用xlrd,xlwt编写一个简单的数据分析程序:

简单需求根据“待分析文件"中第一个sheet中的id值集合过滤第二个sheet中的对应列id的单元格值 相等的行, 并且将这些行输出到“分析结果文件”

待分析文件-sheet1

id
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20

待分析文件-sheet2

id	name	other
1 	xxxx	3
2 	xxxx	4
3 	xxxx	5
4 	xxxx	6
5 	xxxx	7
6 	xxxx	8
7 	xxxx	9
8 	xxxx	10
9 	xxxx	11
10 	xxxx	12
11 	xxxx	13
12 	xxxx	14
13 	xxxx	15
14 	xxxx	16
15 	xxxx	17
16 	xxxx	18
17 	xxxx	19
18 	xxxx	20
19 	xxxx	21
20 	xxxx	22
21 	xxxx	23
22 	xxxx	24
23 	xxxx	25
24 	xxxx	26
25 	xxxx	27
26 	xxxx	28
27 	xxxx	29
28 	xxxx	30
29 	xxxx	31
30 	xxxx	32
31 	xxxx	33
32 	xxxx	34
33 	xxxx	35
34 	xxxx	36
35 	xxxx	37
36 	xxxx	38
37 	xxxx	39
38 	xxxx	40
39 	xxxx	41
40 	xxxx	42
41 	xxxx	43
42 	xxxx	44
43 	xxxx	45
44 	xxxx	46
45 	xxxx	47
46 	xxxx	48

分析代码:

#!/usr/bin/env python3
# coding: utf-8
import xlrd,xlwt

# 打开excel文件,创建一个workbook对象,book对象也就是fruits.xlsx文件,表含有sheet名
rbook = xlrd.open_workbook('待分析的文件.xlsx')
# sheets方法返回对象列表,[<xlrd.sheet.Sheet object at 0x103f147f0>]
rbook.sheets()
# xls默认有3个工作簿,Sheet1,Sheet2,Sheet3
rsheet1 = rbook.sheet_by_index(0)  # 取第1个工作簿
rsheet2 = rbook.sheet_by_index(1)  # 取第2个工作簿
# 循环工作簿的所有行
result = []
for rowt in rsheet1.get_rows():
    id_columnt = rowt[0]  # id所在的列
    id_valuet = id_columnt.value  # 项目名
    if id_valuet != 'id':  # 排除第一行
        result.append(id_valuet)

workbook = xlwt.Workbook(encoding='gbk')
sheet = workbook.add_sheet("Miss")
num = 1

# 取第2个工作簿内容通过取第1个工作簿的集合进行过滤
for row in rsheet2.get_rows():
    id_value2_1 = row[0].value # id所在的列
    name_value2_2 = row[1].value  # name所在的列
    other_value2_3 = row[2].value  # other所在的列
    if id_value2_1 != 'id':  # 排除第一行
        if id_value2_1 in result:
            sheet.write(num, 0, id_value2_1)
            sheet.write(num, 1, name_value2_2)
            sheet.write(num, 2, other_value2_3)
            num += 1
            # print("rsheet2.id=", id_value2_1, "rsheet2.name=", id_value2_2,"rsheet2.other=", id_value2_3)
workbook.save('分析结果数据.xls')


分析结果文件(第二行开始,首行title为补充):

1	xxxx	3
2	xxxx	4
3	xxxx	5
4	xxxx	6
5	xxxx	7
6	xxxx	8
7	xxxx	9
8	xxxx	10
9	xxxx	11
10	xxxx	12
11	xxxx	13
12	xxxx	14
13	xxxx	15
14	xxxx	16
15	xxxx	17
16	xxxx	18
17	xxxx	19
18	xxxx	20
19	xxxx	21
20	xxxx	22
原文地址:https://www.cnblogs.com/golden-elephant/p/12861488.html