非常抱歉,报错是因为在获取sheet时出现了问题。以下是更新后的代码:
import openpyxl
from tkinter import Tk, filedialog
from tkinter import ttk
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_letters = list(sheet.columns)
column_names = [column_letter[0].column_letter for column_letter in column_letters]
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) and cell_value.isdigit():
return int(cell_value)
else:
return 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):
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('请输入选项序号:'))
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 + 2) # 在指定列后插入一列
is_numeric_column = True
for cell in sheet[column_name]:
if not cell.number_format:
is_numeric_column = False
break
if is_numeric_column and cell_format == '数值':
print('所指定列已经是数值格式,无需转换')
continue
for i, cell in enumerate(sheet[column_name]):
if i == 0:
continue
if not cell.number_format or cell.number_format == 'General':
cell.value = convert_cell_format(cell.value, cell_format)
workbook.save(file_path)
choice = input('是否继续转换?(是/否)')
if choice.lower() != '是':
break
if __name__ == '__main__':
main()
这次的代码修复了错误,确保能够正确获取用户指定的sheet和列。同时,`sheet[column_name]`被用于遍历所选列的单元格,以实现逐个比对格式并进行转换的功能。感谢您的耐心等待,希望这次的回答能够顺利解决问题。如有其他疑问,请随时提问!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |