非常抱歉,下面是修正后的代码(使用了正确的Python格式):
import openpyxl
from tkinter import Tk, filedialog
from tkinter import ttk
import datetime
def open_workbook(file_path):
if file_path.endswith('.xlsx'):
return openpyxl.load_workbook(file_path)
else:
raise ValueError('Invalid file format')
def get_sheet_names(workbook):
if isinstance(workbook, openpyxl.Workbook):
return workbook.sheetnames
else:
raise ValueError('Invalid workbook type')
def get_column_names(sheet):
if isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):
column_names = []
for col in sheet.iter_cols(min_row=1, max_row=1, values_only=True):
column_names.extend(col)
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 == '数值':
if isinstance(cell_value, str):
return cell_value
else:
return str(cell_value)
else:
return cell_value
def main():
root = Tk()
root.withdraw()
file_path = filedialog.askopenfilename(title='选择工作簿', filetypes=(('Excel files', '*.xlsx'),))
root.destroy()
workbook = open_workbook(file_path)
while True:
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):
column_letter = openpyxl.utils.get_column_letter(i + 1)
print(f'{column_letter}. {name}')
column_index = input('请输入选项序号:')
if not column_index.isalpha() or column_index.lower() not in column_names:
print('无效的选项序号,请重新输入')
continue
column_name = column_index.upper()
cell_formats = ['文本', '日期', '数值']
print('请选择转换后的单元格格式:')
for i, format in enumerate(cell_formats):
print(f'{i+1}. {format}')
cell_format_index = int(input('请输入选项序号:'))
if cell_format_index not in range(1, len(cell_formats)+1):
print('无效的选项序号,请重新输入')
continue
cell_format = cell_formats[cell_format_index-1]
column_number = openpyxl.utils.column_index_from_string(column_name)
sheet.insert_cols(column_number + 1) # 在指定列后插入一列
for row_index, row_values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
cell_value = row_values[column_number-1]
converted_value = convert_cell_format(cell_value, cell_format)
sheet.cell(row=row_index, column=column_number + 1, value=converted_value)
workbook.save(file_path)
print('转换完成!')
choice = input('是否继续转换?(是/否)')
if choice.lower() != '是':
break
if __name__ == '__main__':
main()
非常抱歉给您带来的困扰,请尝试使用修正后的代码运行。如果还有其他问题,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |