import wx
import openpyxl
from pypinyin import pinyin, Style
import os
class MainFrame(wx.Frame):
def __init__(self):
super().__init__(parent=None, title='Excel中文转拼音缩写工具', size=(500, 300))
self.init_ui()
def init_ui(self):
panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
# 创建文件选择按钮
select_btn = wx.Button(panel, label='选择Excel文件')
select_btn.Bind(wx.EVT_BUTTON, self.on_select)
vbox.Add(select_btn, 0, wx.ALL | wx.CENTER, 20)
# 创建状态显示文本框
self.status_text = wx.TextCtrl(panel, style=wx.TE_MULTILINE | wx.TE_READONLY)
vbox.Add(self.status_text, 1, wx.ALL | wx.EXPAND, 20)
panel.SetSizer(vbox)
self.Centre()
def on_select(self, event):
with wx.FileDialog(self, "选择Excel文件", wildcard="Excel files (*.xlsx)|*.xlsx",
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog:
if fileDialog.ShowModal() == wx.ID_CANCEL:
return
pathname = fileDialog.GetPath()
try:
self.process_excel(pathname)
except Exception as e:
wx.MessageBox(f'处理文件时发生错误:{str(e)}', '错误',
wx.OK | wx.ICON_ERROR)
def get_pinyin_abbr(self, chinese_str):
"""获取中文的拼音缩写"""
if not chinese_str or not isinstance(chinese_str, str):
return chinese_str
# 获取每个字的拼音首字母
abbr = ''
for p in pinyin(chinese_str, style=Style.FIRST_LETTER):
abbr += p[0].upper()
return abbr
def process_excel(self, filepath):
"""处理Excel文件"""
self.status_text.SetValue("开始处理文件...\n")
# 加载工作簿
wb = openpyxl.load_workbook(filepath)
ws = wb.active
# 查找目标列的索引
project_col = None
dept_col = None
for col in range(1, ws.max_column + 1):
cell_value = ws.cell(row=2, column=col).value # 假设第2行是标题行
if cell_value == "项目名称":
project_col = col
elif cell_value == "部门":
dept_col = col
if not project_col or not dept_col:
raise ValueError("未找到'项目名称'或'部门'列")
# 转换内容
changes = []
for row in range(3, ws.max_row + 1): # 从第3行开始处理
# 处理项目名称
project_cell = ws.cell(row=row, column=project_col)
if project_cell.value:
original_project = project_cell.value
project_cell.value = self.get_pinyin_abbr(original_project)
changes.append(f"行 {row}: 项目名称 '{original_project}' -> '{project_cell.value}'")
# 处理部门
dept_cell = ws.cell(row=row, column=dept_col)
if dept_cell.value:
original_dept = dept_cell.value
dept_cell.value = self.get_pinyin_abbr(original_dept)
changes.append(f"行 {row}: 部门 '{original_dept}' -> '{dept_cell.value}'")
# 生成新文件名
file_dir = os.path.dirname(filepath)
file_name = os.path.basename(filepath)
new_file_name = f"pinyin_{file_name}"
new_filepath = os.path.join(file_dir, new_file_name)
# 保存新文件
wb.save(new_filepath)
# 更新状态
status_msg = "\n".join(changes)
self.status_text.AppendText(f"\n转换完成!更改详情:\n{status_msg}\n\n新文件已保存为:{new_filepath}")
def main():
app = wx.App()
frame = MainFrame()
frame.Show()
app.MainLoop()
if __name__ == '__main__':
main()
|