非常抱歉对之前的回答误解了您的需求。以下是经过修改的代码,实现了用户在打开文件对话框中选择工作簿的功能:
import openpyxl
import xlrd
import tkinter as tk
from tkinter import filedialog
def open_workbook(file_path):
if file_path.endswith('.xls'):
return xlrd.open_workbook(file_path)
elif file_path.endswith('.xlsx'):
return openpyxl.load_workbook(file_path)
else:
raise ValueError('Invalid file format')
def get_sheet_names(workbook):
if isinstance(workbook, xlrd.Book):
return workbook.sheet_names()
elif isinstance(workbook, openpyxl.Workbook):
return workbook.sheetnames
else:
raise ValueError('Invalid workbook type')
def get_column_names(sheet):
if isinstance(sheet, xlrd.Sheet):
return sheet.row_values(0)
elif isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):
column_names = []
for col in sheet.iter_cols(min_row=1, max_row=1):
column_names.append(col.value)
return column_names
else:
raise ValueError('Invalid sheet type')
def convert_cell_format(cell_value, cell_format):
if cell_format == '文本':
if isinstance(cell_value, (int, float)):
return str(cell_value)
else:
return cell_value
elif cell_format == '日期':
if isinstance(cell_value, str):
return datetime.datetime.strptime(cell_value, '%Y-%m-%d').date()
else:
return cell_value
elif cell_format == '常规':
return cell_value
elif cell_format == '数值':
if isinstance(cell_value, str):
try:
return float(cell_value)
except ValueError:
return cell_value
else:
return cell_value
else:
return cell_value
def main():
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(title='选择工作簿', filetypes=[('Excel Files', '*.xls;*.xlsx')])
if not file_path:
print('未选择工作簿,程序退出。')
return
workbook = open_workbook(file_path)
sheet_names = get_sheet_names(workbook)
print('请选择要操作的sheet:')
for i, name in enumerate(sheet_names):
print(f'{i+1}. {name}')
sheet_index = int(input('请输入选项序号:')) - 1
sheet = workbook[sheet_names[sheet_index]]
column_names = get_column_names(sheet)
print('请选择要转换格式的列:')
for i, name in enumerate(column_names):
print(f'{i+1}. {name}')
column_index = int(input('请输入选项序号:')) - 1
column_name = column_names[column_index]
cell_formats = ['文本', '日期', '常规', '数值']
print('请选择转换后的单元格格式:')
for i, format in enumerate(cell_formats):
print(f'{i+1}. {format}')
cell_format_index = int(input('请输入选项序号:')) - 1
cell_format = cell_formats[cell_format_index]
sheet.insert_cols(column_index + 2)
for i, cell in enumerate(sheet[column_index]):
if i == 0:
cell.style = None # 清除单元格的样式
cell.value = convert_cell_format(cell.value, cell_format)
style = openpyxl.styles.Style(number_format='@') if cell_format == '文本' else None
cell.style = style
workbook.save(file_path)
choice = input('是否继续转换?(是/否)')
if choice.lower() == '是':
main()
else:
print('程序退出。')
if __name__ == '__main__':
main()
这次代码会弹出一个文件对话框让用户选择工作簿,然后再继续后续的操作。请确保在运行代码之前安装了Tkinter库,可以使用`pip install tkinter`命令进行安装。
希望这次满足了您的需求,请再次接受我诚挚的道歉。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |