|
发表于 2024-3-22 17:15:12
|
显示全部楼层
非常抱歉,下面是修改后的代码,已按照Python格式进行调整:import sys
from PySide6 import QtCore, QtWidgets
from PySide6.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
import pandas as pd
class ExcelConverter(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Excel转换器")
self.resize(400, 300)
self.workbook_path = ""
self.sheet_names = []
self.column_names = []
self.central_widget = QtWidgets.QWidget(self)
self.setCentralWidget(self.central_widget)
self.file_label = QtWidgets.QLabel(self.central_widget)
self.file_label.setGeometry(QtCore.QRect(20, 20, 361, 16))
self.file_label.setText("请选择要打开的工作簿:")
self.file_button = QtWidgets.QPushButton(self.central_widget)
self.file_button.setGeometry(QtCore.QRect(20, 50, 101, 31))
self.file_button.setText("选择文件")
self.file_button.clicked.connect(self.open_workbook)
self.sheet_label = QtWidgets.QLabel(self.central_widget)
self.sheet_label.setGeometry(QtCore.QRect(20, 100, 191, 16))
self.sheet_label.setText("请选择要操作的Sheet:")
self.sheet_combobox = QtWidgets.QComboBox(self.central_widget)
self.sheet_combobox.setGeometry(QtCore.QRect(20, 130, 361, 31))
self.sheet_combobox.currentIndexChanged.connect(self.load_columns)
self.column_label = QtWidgets.QLabel(self.central_widget)
self.column_label.setGeometry(QtCore.QRect(20, 180, 191, 16))
self.column_label.setText("请选择要转换格式的列:")
self.column_combobox = QtWidgets.QComboBox(self.central_widget)
self.column_combobox.setGeometry(QtCore.QRect(20, 210, 361, 31))
self.format_label = QtWidgets.QLabel(self.central_widget)
self.format_label.setGeometry(QtCore.QRect(20, 260, 191, 16))
self.format_label.setText("请选择转换后的格式:")
self.format_combobox = QtWidgets.QComboBox(self.central_widget)
self.format_combobox.setGeometry(QtCore.QRect(20, 290, 361, 31))
self.convert_button = QtWidgets.QPushButton(self.central_widget)
self.convert_button.setGeometry(QtCore.QRect(150, 340, 101, 31))
self.convert_button.setText("开始转换")
self.convert_button.clicked.connect(self.convert_data)
def open_workbook(self):
file_dialog = QFileDialog()
file_dialog.setFileMode(QFileDialog.AnyFile)
file_dialog.setNameFilter("Excel 文件 (*.xls *.xlsx)")
if file_dialog.exec_():
self.workbook_path = file_dialog.selectedFiles()[0]
self.file_label.setText(f"选择的工作簿:{self.workbook_path}")
self.load_sheets()
def load_sheets(self):
self.sheet_combobox.clear()
try:
sheets = pd.read_excel(self.workbook_path, sheet_name=None)
self.sheet_names = list(sheets.keys())
self.sheet_combobox.addItems(self.sheet_names)
except Exception as e:
QMessageBox.critical(self, "错误", f"无法打开工作簿:{e}")
def load_columns(self):
self.column_combobox.clear()
selected_sheet = self.sheet_combobox.currentText()
try:
df = pd.read_excel(self.workbook_path, sheet_name=selected_sheet, header=None)
self.column_names = df.iloc[0].tolist()
self.column_combobox.addItems(self.column_names)
except Exception as e:
QMessageBox.critical(self, "错误", f"无法读取工作簿的列名:{e}")
def convert_data(self):
selected_sheet = self.sheet_combobox.currentText()
selected_column = self.column_combobox.currentText()
selected_format = self.format_combobox.currentText()
try:
df = pd.read_excel(self.workbook_path, sheet_name=selected_sheet)
if selected_column == "转换后列":
QMessageBox.warning(self, "警告", "请选择有效的列")
return
if selected_format == "数值" and df[selected_column].dtype != object:
QMessageBox.warning(self, "警告", "已经是数值类型的列不能再转换为数值")
return
if selected_format == "文本":
df[selected_column] = df[selected_column].astype(str)
elif selected_format == "日期":
df[selected_column] = pd.to_datetime(df[selected_column], errors="coerce").dt.strftime("%Y-%m-%d")
elif selected_format == "数值":
df[selected_column] = pd.to_numeric(df[selected_column], errors="coerce")
if selected_column == "身份证号":
df[selected_column] = df[selected_column].apply(self.convert_id_to_str)
df["转换后列"] = ""
save_path, _ = QFileDialog.getSaveFileName(filter="Excel 文件 (*.xlsx)")
if save_path:
with pd.ExcelWriter(save_path) as writer:
df.to_excel(writer, sheet_name=selected_sheet, index=False)
reply = QMessageBox.question(self, "询问", "转换成功!是否继续转换?", QMessageBox.Yes | QMessageBox.No)
if reply == QMessageBox.Yes:
self.column_combobox.clear()
self.format_combobox.clear()
else:
sys.exit()
except Exception as e:
QMessageBox.critical(self, "错误", f"转换失败:{e}")
def convert_id_to_str(self, x):
if isinstance(x, str):
return x
return str(int(x))
if __name__ == "__main__":
app = QApplication(sys.argv)
converter = ExcelConverter()
converter.show()
sys.exit(app.exec())再次对前面的错误表示歉意,希望这次的修改能够解决问题。如果还有其他问题,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|