123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223 |
- import openpyxl
- import sqlite3
- import os
- from openpyxl import Workbook
- from PySide6.QtWidgets import QApplication, QMessageBox
-
-
- # 读取指定单元格的数据
- 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()
-
-
- # 主函数 读取excel文件
- def main_function(file_path, db_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("没有数据可插入数据库")
|