lesten

可以使用 openpyxl、pandas、openpyxl、xlsxwriter、xlwings、pywin32、 xlrd or xlwt 等py库 进行excel读写;

以下通过 xlrd 和 xlwt

pip install xlrd

pip install xlwt

import xlrd

#
1、打开文件 exceld = xlrd.open_workbook(excelpath) # 2、获取表单对象 print \'表单名字:\', exceld.sheet_names() print \'表单数量:\', exceld.nsheets print \'表单对象:\', exceld.sheets() print \'通过名字查找:\', exceld.sheet_by_name("test") print \'通过索引查找:\', exceld.sheet_by_index(0) data = xlrd.open_workbook(excelpath) table = data.sheet_by_index(0) for rowCount in range(table.nrows): val = (table.row_values(rowCount)) for v in val: print v

这就完成了对excel基本数据的遍历

API: https://xlrd.readthedocs.io/en/latest/api.html#module-xlrd

 

Demo:读取 身份证号码判断年龄大于60岁 写入另一个xls

#coding:utf-8
import xlrd
import xlwt

excelpath = "E:\\xyldy.xls"
excel_retpath = "E:\\result.xls"

# 1、打开文件
exceld = xlrd.open_workbook(excelpath)

# 2、读取数据
data = xlrd.open_workbook(excelpath)
# 选择表单
table = data.sheet_by_index(0)

# 3、准备写结果xls 添加结果表单
workbook = xlwt.Workbook()
sheet = workbook.add_sheet("result")

# 4、读取 身份证号码判断年龄大于60岁 写入结果
for rowCount in range(table.nrows):
    val = (table.row_values(rowCount))
    a = val[2][6:10].encode("utf-8")
    if len(a) == 4:
        year = int(a)
        
        if (2020 - year) > 60:
            for i in range(0, len(val)):
                sheet.write(index, i, val[i])
            index = index + 1
        else:
            print "age = " + str((2020 - year)) 
    else:
        print a

# 5、保存文件
workbook.save(excel_retpath) 

 

分类:

技术点:

相关文章: