1. 程式人生 > 實用技巧 >Python實現excel的查詢與替換(轉EXE後可直接執行)

Python實現excel的查詢與替換(轉EXE後可直接執行)

#如果看不懂聯絡Q:18081530 
#如需轉載請聯絡,或註明出處,否則追究法律責任。

#excel openpyxl庫 和os 庫的使用。




import openpyxl
import os

excle = os.getcwd() #獲取當前目錄路徑
file = os.listdir(excle) # 開啟當前檔名

length = len(file)
for num in range(0,length) :
#獲取表格名字
file_name = file[num]
if os.path.splitext(file_name)[1] == '.xlsx' :
# 【0】陣列是檔名,【1】陣列是字尾名
# 如果是xlsx檔案
# work_name = print(file_name) # excel 名
wb = openpyxl.load_workbook(file_name)
ws = wb.active
#print(ws)

#選單
def print_menu():
print("-"*30)
# print("excel系統V1.0")
print("1.查看錶格內容")
print("2.查詢指定文字")
print("3.修改文字")
print("0.退出系統")
print("-" * 30)

a = []
# 遍歷 excel的內容
def work_ex():
for row in ws.rows:
for cell in row:
cell.value
a.append(cell.value)
print(a)

cishu = 0
def replace_Word():
find_target = input('請輸入原文字判斷是否在excel中存在:')

for i in range(15):
if find_target == a[i]:
print("存在")
break
else:
continue
else:
print("不存在")

# 替換文字
def xiugai():

wz = input('請輸入修改的位置(如:A1) :')
nr = input('請輸入修改的內容:')
ws[wz] = nr
wb.save('修改後.xlsx')
print("修改成功")

#主選單
def main():
while True:
print_menu() #列印功能選單
number = input("請選擇功能:")
if number == "1": #查看錶格內容
work_ex()

elif number == "2": #查詢指定文字
replace_Word()
elif number == "3": # 修改指定文字
xiugai()
elif number == "0": # 退出系統
print("退出成功,歡迎下次使用!")
break

print("歡迎登陸!")
#if __name__ == '__main__':
main()