Excel 表格数据筛选操作

import csv
from tkinter.filedialog import askopenfilename
import tkinter as tk
import xlrd


'''
# 打开对话框 Tkinter
# 获取文件路径
# 安装python官方Excel库--xlrd
# 获取Excel文件位置并读取
# 读取sheet表
# 读取指定rows内容
# Excel文件作为被筛选文件,
# csv文件作为筛选条件

'''

root = tk.Tk()
root.withdraw()
# 打开文件获取路径
excel_path = askopenfilename(initialdir='.')
while not excel_path:
    excel_path = askopenfilename(initialdir='.')
wb = xlrd.open_workbook(filename=excel_path)
sheet1 = wb.sheet_by_index(0)  # 通过索引获取第一张表格
csv_path = askopenfilename(initialdir='.')
while not csv_path:
    csv_path = askopenfilename(initialdir='.')
with open(csv_path, 'r', encoding='utf-8', errors='ignore') as area_code: # 如果读取错误将编码格式去掉
    csv_reader = csv.reader(area_code)
    code_list = list(csv_reader)

number = 0
for i in range(sheet1.nrows):
    code = sheet1.row_values(i)
    flag = True		# 转换开关,True为将跳过重复项,False为将重复项的留下
    for li in code_list:
        if code[-1] == li[-1]:
            number += 1	# 计算有多少符合条件的,便于核对数据
            flag = False 	# 转换开关, 与第一个flag互斥
    if flag:
        with open('筛选结果.csv', 'a+', encoding='utf-8', newline='') as csv_file:
            csv_writer = csv.writer(csv_file)
            csv_writer.writerow(code)
print(number)

你可能感兴趣的:(Python文档)