import openpyxl import sqlite3 import os import pandas as pd from openpyxl import Workbook from PySide6.QtWidgets import QApplication, QMessageBox # 添加文件转换函数 def convert_xls_to_xlsx(file_path): # 使用 pandas 读取 .xls 文件 df = pd.read_excel(file_path, engine='xlrd') # 创建一个新的 .xlsx 文件路径 xlsx_file_path = file_path.replace('.xls', '.xlsx') # 将数据保存为 .xlsx 文件 df.to_excel(xlsx_file_path, index=False) return xlsx_file_path # 弹窗提示用户 .xls 文件将转换为 .xlsx 文件 def confirm_xls_to_xlsx_conversion(file_name): response = QMessageBox.question(None, "确认转换", f".xls文件将默认转换为.xlsx文件进行计算,系统会重新生成一个.xlsx文件副本用以计算,不会删除您本来的.xls文件,点击“OK”开始上传文件,点击“Cancel”取消上传文件", QMessageBox.Ok | QMessageBox.Cancel) return response == QMessageBox.Ok # 读取指定单元格的数据 def read_cells_from_excel(cells, sheet): """ 读取指定单元格的数据并返回字典。 """ cell_values = {} for cell in cells: cell_values[cell] = sheet[cell].value return cell_values # 获取最后一行有数字的单元格值 def get_last_numeric_cell_value(sheet, column): """ 获取指定列的最后一行有数字的单元格的值。 """ last_row = sheet.max_row for row in range(last_row, 0, -1): cell_value = sheet[f"{column}{row}"].value if isinstance(cell_value, (int, float)): return cell_value return None # 计算指定列中数值型数据的总和 def calculate_column_sum(sheet, column): """ 计算指定列中数值型数据的总和。 """ total_sum = 0 for row in range(1, sheet.max_row + 1): cell_value = sheet[f"{column}{row}"].value if isinstance(cell_value, (int, float)): total_sum += cell_value return total_sum # 读取Excel文件并计算公式结果 def load_and_calculate_excel(file_path): # 加载Excel文件并计算单元格H1的公式结果。 workbook = openpyxl.load_workbook(file_path, data_only=True) sheet = workbook.active h1_value = sheet['H1'].value return h1_value # 弹窗提示用户是否更新数据 def ask_for_update(file_name): response = QMessageBox.question(None, "提示", f"检测到数据库中存在相同文件 '{file_name}',是(Yes)否(No)更新数据?", QMessageBox.Yes | QMessageBox.No) return response == QMessageBox.Yes # 数据库插入函数,插入数据到GC_Input_Param中 def insert_into_database(file_name, cell_values, ms_station, last_station_count, new_station_count, last_sum_hdiff, new_sum_hdiff, last_sum_rlen, new_sum_rlen, db_path, file_name_utf8): """ 将文件名和结果名称插入或更新到数据库的GC_Input_Param表中。 """ database = db_path conn = sqlite3.connect(database=database) cursor = conn.cursor() try: # 查询是否已存在相同的记录 cursor.execute( "SELECT * FROM GC_Input_Param WHERE TableName = ?", (file_name_utf8,) ) existing_record = cursor.fetchone() if existing_record: # 弹窗询问用户是否更新数据 if not ask_for_update(file_name): print("用户选择不更新数据") return # 更新现有记录 cursor.execute( """ UPDATE GC_Input_Param SET Last_ResultName = ?, ObservationLevel = ?, New_ResultName = ?, Ms_Station = ?, Last_StationCount = ?, New_StationCount = ?, Last_SumHDiff = ?, New_SumHDiff = ?, Last_SumRLen = ?, New_SumRLen = ? WHERE TableName = ? """, (cell_values['D1'], cell_values['C1'], cell_values['I1'], ms_station, last_station_count, new_station_count, last_sum_hdiff, new_sum_hdiff, last_sum_rlen, new_sum_rlen, file_name_utf8) ) QMessageBox.information(None, "提示", f"文件 '{file_name}' 已成功更新到本地数据库中,点击'OK'以关闭此对话框。对话框关闭后,请点击“计算”以重新计算数据") else: # 插入新记录 cursor.execute( """ INSERT INTO GC_Input_Param (TableName, Last_ResultName, ObservationLevel, New_ResultName, Ms_Station, Last_StationCount, New_StationCount, Last_SumHDiff, New_SumHDiff, Last_SumRLen, New_SumRLen) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( file_name_utf8, cell_values['D1'], cell_values['C1'], cell_values['I1'], ms_station, last_station_count, new_station_count, last_sum_hdiff, new_sum_hdiff, last_sum_rlen, new_sum_rlen) ) QMessageBox.information(None, "提示", f"文件 '{file_name}' 已成功添加到本地数据库中,点击'OK'以关闭此对话框。对话框关闭后,请点击“计算”以计算数据") conn.commit() except sqlite3.Error as e: print(f"插入或更新文件名时发生错误: {e}") except Exception as e: print(f"处理文件时发生错误: {e}") finally: conn.close() # 遍历获取序号的数据 def get_data_from_excel(file_path): """ 从 Excel 文件中获取对应列的数据。 """ workbook = openpyxl.load_workbook(file_path) sheet = workbook.active data = [] for row in range(3, sheet.max_row + 1): a_value = sheet[f"A{row}"].value b_value = sheet[f"B{row}"].value c_value = sheet[f"C{row}"].value d_value = sheet[f"D{row}"].value e_value = sheet[f"E{row}"].value f_value = sheet[f"F{row}"].value g_value = sheet[f"G{row}"].value h_value = sheet[f"H{row}"].value i_value = sheet[f"I{row}"].value j_value = sheet[f"J{row}"].value if a_value is not None or f_value is not None: data.append((a_value, b_value, c_value, d_value, e_value, f_value, g_value, h_value, i_value, j_value)) return data # 插入点数据到GC_Input_Point中 def insert_data_into_database(data, file_name, cell_values, db_path, file_name_utf8): """ 将数据插入到数据库表 GC_Input_Point 中。如果 TableName 相同,则清空表, 然后插入新的数据。 """ database = db_path conn = sqlite3.connect(database=database) cursor = conn.cursor() try: # 检查是否已存在相同的 TableName cursor.execute( "SELECT * FROM GC_Input_Point WHERE TableName = ?", (file_name_utf8,) ) existing_record = cursor.fetchone() if existing_record: # 如果存在相同的 TableName,清空表 cursor.execute("DELETE FROM GC_Input_Point WHERE TableName = ?", (file_name_utf8,)) conn.commit() # 插入新数据 for a_value, b_value, c_value, d_value, e_value, f_value, g_value, h_value, i_value, j_value in data: cursor.execute( """ INSERT INTO GC_Input_Point (Last_ID, Last_SPName, Last_EPName,Last_HDiff,Last_RLen, New_ID, New_SPName, New_EPName,New_HDiff,New_RLen, TableName, Last_ResultName, New_ResultName) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, (a_value, b_value, c_value, d_value, e_value, f_value, g_value, h_value, i_value, j_value, file_name_utf8, cell_values['D1'], cell_values['I1']) ) conn.commit() except sqlite3.Error as e: print(f"插入或更新点数据时发生错误: {e}") except Exception as e: print(f"处理文件时发生错误: {e}") finally: conn.close() # 读取指定单元格的数据(编辑) def read_cells_from_excel1(list1): cell_values = {} cell_values['D1'] = list1[0][1] cell_values['C1'] = list1[0][11] cell_values['I1'] = list1[0][6] return cell_values # 获取最后一行有数字的单元格值(编辑) def get_last_numeric_cell_value1(list1, index): ii = 0 while ii < len(list1): if list1[ii][index] == '' or list1[ii][index] == ' ' or list1[ii][index] == None: ii = ii + 1 break else: ii = ii + 1 return ii # 计算指定列中数值型数据的总和(编辑) def calculate_column_sum1(list1, index): sum = 0 for li in list1: if li[index] == '' or li[index] == ' ' or li[index] == None: break else: sum = sum + float(li[index]) return sum # 遍历获取序号的数据(修改数据) def get_data_from_excel1(list1): data = [] for row in range(len(list1)): a_value = list1[row][0] b_value = list1[row][2] c_value = list1[row][3] try: d_value = float(list1[row][4]) e_value = float(list1[row][5]) except: d_value = None e_value = None f_value = list1[row][0] g_value = list1[row][7] h_value = list1[row][8] try: i_value = float(list1[row][9]) j_value = float(list1[row][10]) except: i_value = None j_value = None if a_value is not None or f_value is not None: data.append((a_value, b_value, c_value, d_value, e_value, f_value, g_value, h_value, i_value, j_value)) return data # 主函数 读取excel文件 def main_function(file_path, db_path): # 检查文件扩展名 if file_path.endswith('.xls'): # 弹窗提示用户 .xls 文件将转换为 .xlsx 文件 if not confirm_xls_to_xlsx_conversion(os.path.basename(file_path)): print("用户取消了转换操作") return # 转换 .xls 文件为 .xlsx 文件 file_path = convert_xls_to_xlsx(file_path) # 调用读取Excel文件的函数 file_name = os.path.basename(file_path) file_name_utf8 = file_name.encode('utf-8') # 加载工作簿 workbook = openpyxl.load_workbook(file_path) sheet = workbook.active # 计算单元格 H1 的公式结果 ms_station = load_and_calculate_excel(file_path) # 读取指定单元格的数据 cells_to_read = ['D1', 'C1', 'I1'] cell_values = read_cells_from_excel(cells_to_read, sheet) # 获取最后一行有数字的单元格值 last_station_count = get_last_numeric_cell_value(sheet, 'A') new_station_count = get_last_numeric_cell_value(sheet, 'F') # 计算 D 列和 I 列中数值型数据的总和 总高差 last_sum_hdiff = calculate_column_sum(sheet, 'D') new_sum_hdiff = calculate_column_sum(sheet, 'I') # 总路线长 last_sum_rlen = calculate_column_sum(sheet, 'E') new_sum_rlen = calculate_column_sum(sheet, 'J') # 插入点的数组 data = get_data_from_excel(file_path) # 调用插入数据库的函数 if file_name: insert_into_database(file_name, cell_values, ms_station, last_station_count, new_station_count, last_sum_hdiff, new_sum_hdiff, last_sum_rlen, new_sum_rlen, db_path, file_name_utf8) insert_data_into_database(data, file_name, cell_values, db_path, file_name_utf8) else: print("没有数据可插入数据库")