python基础学完后,为了巩固基础语法,可以做一些办公自动化的练习。通过高效地从成千上万条无序记录中提取需要的信息,可以切实感受到Python的强大与简洁。从而达到进一步深入Python实战项目的动力。
Python的第三方库模块openpyxl实现从Excel提取信息的主要步骤如下:
1.导入 openpyxl 模块。
2.调用 openpyxl.load_workbook()函数。
3.取得 Workbook工作簿对象。
4.调用 get_active_sheet()或 get_sheet_by_name()方法。
5.取得 Worksheet 工作表对象。
import openpyxl
lines = []
count = 0
wb = openpyxl.load_workbook('/home/lijiang/Excel人员数据/营盘居民缴费应申报未申报.xlsx')
sheet = wb['营盘街办']
for row in range(2, 2419):
name = sheet['C' + str(row)].value
identity = sheet['A' + str(row)].value
community = sheet['I' + str(row)].value
Type = sheet['M' + str(row)].value
record = name + ' ' + identity + ' ' + community + ' ' + Type
if community == '南十方张家巷社区居委会':
count = count + 1
print(str(count) + ' ' + record)
lines.append(record)
with open('/home/lijiang/Excel人员数据/提取结果.txt', 'w') as file:
for line in lines:
file.write(line+'\n')
通过引用相应的列名,从中取得单元格的数据。然后通过条件判断语句,只输出符合字符串条件的行记录。并依次追加到列表中。最后将符合条件的记录写入一个文本文件中,实现数据持久化。