import configparser import os.path import re from datetime import datetime import os.path import tkinter from tkinter import * from tkinter import filedialog from tkinter.ttk import * from tkinter.messagebox import * import numpy as np import pandas as pd # table_list = [] ini_path = '' app_name = '' excel_path = '' dsl_path = '' log_path_list = [] config_path = '' class ReplaceFileKey: def __init__(self, file_name): self.file_name = file_name self.file_lines = [] # 查找是否包含标记信息 def find_key_word(self, key_flag_infor, line_infor): if line_infor.find(key_flag_infor) != -1: print('Match') return True return False # 字符串如果符合匹配条件,则进行替换 def replace_key_word(self, line_infor, regexp, target): pattern_re = re.compile(regexp) match_result = pattern_re.search(line_infor) if match_result: key_word = "{}".format(match_result.group(1)) results = re.sub(key_word, target, line_infor) print(results) return results return '' def read_infor_by_line(self): self.file_lines.clear() with open(self.file_name, "r", encoding="utf-8") as file: self.file_lines = file.readlines() return True return False def read_infor_by_line(self): if not os.path.exists(self.file_name): return False self.file_lines.clear() with open(self.file_name, "r", encoding="utf-8") as file: self.file_lines = file.readlines() return True return False def write_infor_by_line(self): with open(self.file_name, "w", encoding="utf-8") as file: file.writelines(self.file_lines) def rename_file(self): now = datetime.now() newname = now.strftime("_%Y%m%d%H%M%S.bak") print(self.file_name + newname) os.rename(self.file_name, self.file_name + newname) def find_and_replace_key_word(self, key_flag_infor, regexp, target): start_match = False for i, line in enumerate(self.file_lines): if not start_match: if self.find_key_word(key_flag_infor, line): start_match = True if key_flag_infor == '': start_match = True if not start_match: continue new_line = self.replace_key_word(line, regexp, target) if new_line != '': print(new_line) self.file_lines[i] = new_line return True return False def get_head_list(self, get_data_xlsx): print('get_head_list') list_str = [] pdf = self.read_src_data(get_data_xlsx) list_str = pdf.columns.tolist() for head_iterm in list_str: if head_iterm.find("Unnamed:") != -1: list_str.remove(head_iterm) print(list_str) return list_str def read_src_data_excel(self,excel_path): # 读取Excel文件 df = pd.read_excel(excel_path, engine='openpyxl') return df def read_src_data_csv(self, excel_path): # 读取Excel文件 df = pd.read_csv(excel_path) return df def read_src_data(self, excel_path): if excel_path.endswith('.csv'): return self.read_src_data_csv(excel_path) else: return self.read_src_data_excel(excel_path) def create_html(self, get_data_xlsx): list_infor = [] list_infor.append("<!DOCTYPE html>") list_infor.append("<html lang=\"en\">") list_infor.append("<head><meta charset=\"UTF-8\">") list_infor.append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">") list_infor.append("<title>数据文件转换成HTML</title><script src=\"js/jquery-3.6.0.js\"></script>") list_infor.append("<script type=\"text/javascript\" src=\"js/jquery.dataTables.min.js\"></script>") list_infor.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"js/jquery.dataTables.min.css\">") list_infor.append("</head><style>") list_infor.append("table {border-collapse: collapse;width: 50%;margin: 0 auto;}") list_infor.append("th, td {border: 1px solid rgb(160, 101, 52);padding: 8px; text-align: center;}") list_infor.append("th {background-color: #f2f2f2;}") list_infor.append("</style>") list_infor.append("<body>") list_infor.append("<table id=\"example\" class=\"display\" style=\"width:100%\"><thead><tr>") txt_str = self.get_head_list(get_data_xlsx) temp = '' for h in txt_str: temp = "<th>{}</th>".format(h) print(temp) list_infor.append(temp) # list_infor.append("<th>序号</th><th>CPK</th><th>测试项</th><th>门限</th>") list_infor.append("</tr></thead><tbody>") pda = self.read_src_data(get_data_xlsx) for index, row in pda.iterrows(): list_infor.append('<tr>') for cell in row: temp = "<td>{}</td>".format(cell) list_infor.append(temp) list_infor.append('</tr>') # list_infor.append("<tr><td>1</td><td>25</td><td>程序员/td><td>程序员</td> </tr>") list_infor.append("</tbody></table><script src=\"create-table.js\"></script></body></html>") list_infor.append("<div> Data From:[" + get_data_xlsx + "]</div>") list_infor.append("</body></html>") html_infor = '' for txt in list_infor: html_infor = html_infor + txt now = datetime.now() newname = now.strftime("_%Y%m%d%H%M%S.html") with open("D:\\Testlog\\" + 'test_infor_convert' + newname, 'w', encoding='utf-8') as file: file.write(html_infor) create_table_infor = [] create_table_infor.append("$(document).ready(function() {") create_table_infor.append("$('#example').DataTable();") create_table_infor.append("});") js_infor = '' for js in create_table_infor: js_infor = js_infor + js with open("D:\\Testlog\\" + 'create-table.js', 'w', encoding='utf-8') as file: file.write(js_infor) os.system("start " + "D:\\Testlog\\" + 'test_infor_convet.html') class WinGUI(Tk): def __init__(self): super().__init__() self.__win() self.tk_button_run = self.__tk_button_run(self) self.tk_button_select = self.__tk_button_Select_dsl(self) self.tk_input_path = self.__tk_input_path(self) self.tk_button_lrxiumtm = self.__tk_button_lrxiumtm(self) self.tk_input_log = self.__tk_input_log(self) self.excel_path = excel_path self.dsl_path = dsl_path self.excel_colum_num = 0 def __win(self): self.title(app_name) # 设置窗口大小、居中 width = 1200 height = 200 screenwidth = self.winfo_screenwidth() screenheight = self.winfo_screenheight() geometry = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) self.geometry(geometry) self.resizable(width=False, height=False) def scrollbar_autohide(self, vbar, hbar, widget): """自动隐藏滚动条""" def show(): if vbar: vbar.lift(widget) if hbar: hbar.lift(widget) def hide(): if vbar: vbar.lower(widget) if hbar: hbar.lower(widget) hide() widget.bind("<Enter>", lambda e: show()) if vbar: vbar.bind("<Enter>", lambda e: show()) if vbar: vbar.bind("<Leave>", lambda e: hide()) if hbar: hbar.bind("<Enter>", lambda e: show()) if hbar: hbar.bind("<Leave>", lambda e: hide()) widget.bind("<Leave>", lambda e: hide()) def v_scrollbar(self, vbar, widget, x, y, w, h, pw, ph): widget.configure(yscrollcommand=vbar.set) vbar.config(command=widget.yview) vbar.place(relx=(w + x) / pw, rely=y / ph, relheight=h / ph, anchor='ne') def h_scrollbar(self, hbar, widget, x, y, w, h, pw, ph): widget.configure(xscrollcommand=hbar.set) hbar.config(command=widget.xview) hbar.place(relx=x / pw, rely=(y + h) / ph, relwidth=w / pw, anchor='sw') def create_bar(self, master, widget, is_vbar, is_hbar, x, y, w, h, pw, ph): vbar, hbar = None, None if is_vbar: vbar = Scrollbar(master) self.v_scrollbar(vbar, widget, x, y, w, h, pw, ph) if is_hbar: hbar = Scrollbar(master, orient="horizontal") self.h_scrollbar(hbar, widget, x, y, w, h, pw, ph) self.scrollbar_autohide(vbar, hbar, widget) def __tk_button_Select_dsl(self, parent): btn = Button(parent, text="选择文件", command=self.get_dsl_path) btn.place(x=1100, y=96, width=93, height=40) return btn def __tk_button_run(self, parent): btn = Button(parent, text="运行", command=self.run) btn.place(x=450, y=140, width=300, height=60) return btn def __tk_input_path(self, parent): ipt = Entry(parent, ) ipt.place(x=4, y=21, width=1090, height=40) ipt.delete(0, tkinter.END) # 删除现有内容 ipt.insert(0, excel_path) return ipt def __tk_button_lrxiumtm(self, parent): btn = Button(parent, text="选择文件", command=self.get_path) btn.place(x=1100, y=23, width=95, height=40) return btn def __tk_input_log(self, parent): ipt = Entry(parent, ) ipt.place(x=5, y=95, width=1090, height=40) ipt.delete(0, tkinter.END) # 删除现有内容 ipt.insert(0, dsl_path) return ipt def read_src_data_excel(self, excel_path): # 读取Excel文件 df = pd.read_excel(excel_path, engine='openpyxl') return df def get_path(self): path = filedialog.askopenfilename() self.tk_input_path.delete(0, tkinter.END) # 删除现有内容 self.tk_input_path.insert(0, path) if os.path.exists(path): self.excel_path = path print(path) else: self.tk_input_log.delete(0, tkinter.END) # 删除现有内容 self.tk_input_log.insert(0, "file not exists") def get_dsl_path(self): path = filedialog.askopenfilename() self.tk_input_log.delete(0, tkinter.END) # 删除现有内容 self.tk_input_log.insert(0, path) if os.path.exists(path): self.dsl_path = path print(path) else: self.tk_input_log.delete(0, tkinter.END) # 删除现有内容 self.tk_input_log.insert(0, "file not exists") def run(self): print('run hello') # pdf = self.read_src_data_excel(self.excel_path) replaceopt = ReplaceFileKey(self.excel_path) list_heads_infor = [] list_heads_infor = replaceopt.get_head_list(self.excel_path) print(list_heads_infor) replaceopt.create_html(self.excel_path) if excel_path != self.excel_path: write_ini_value(path_infor + 'config.ini', 'excel_path', self.excel_path) print(showinfo(title="TipsInfor", message="=== Done ===")) class Win(WinGUI): def __init__(self, controller): self.ctl = controller super().__init__() self.__event_bind() self.__style_config() self.ctl.init(self) def __event_bind(self): pass def __style_config(self): pass def read_ini_value(path, key): # 创建一个ConfigParser对象 config = configparser.ConfigParser() # 读取INI文件 config.read(path + 'config.ini') # 获取指定section和key的值 value = config.get(key, 'value') print(value) return value def write_ini_value(path, key, value): # 创建一个ConfigParser对象 config = configparser.ConfigParser() # 读取INI文件 config.read(path) # 修改指定section和key的值 config.set(key, 'value', value) # 将更改写回INI文件 with open(path, 'w') as configfile: config.write(configfile) return True if __name__ == "__main__": path_infor = os.getcwd() path_infor = path_infor + '\\' run_dir = path_infor ini_path = read_ini_value(path_infor,'current_path') app_name = read_ini_value(path_infor, 'app_name') excel_path = read_ini_value(path_infor, 'excel_path') dsl_path = read_ini_value(path_infor, 'dsl_path') print('++:' + path_infor) print('++:' + app_name) config_path = path_infor + 'config.ini' if ini_path != path_infor + 'config.ini': write_ini_value(config_path, 'current_path', config_path) # config_path win = WinGUI() win.mainloop() replace.xlsx
index | key_flag | regexp | target |
1 | name | target2:(\S+) | CC |
2 | name | target3:(\S+) | CC |
=======================config.ini ====================
[app_name]
value = Change_dsl_tool
[current_path]
value = D:\PycharmProjects\pythonProject\ConvertToHtml\config.ini
[excel_path]
value = D:/test_all_result4.csv
[dsl_path]
value = D:\PycharmProjects\pythonProject\ReplaceTxtContent\file.txt