|
发表于 2024-3-20 09:23:33
|
显示全部楼层
非常抱歉给您带来困扰。根据错误提示,是因为`xlrd`库中没有`Sheet`属性。我修改了代码以解决这个问题,请尝试以下代码:
- import openpyxl
- import xlrd
- from tkinter import Tk, 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.Sheet):
- return sheet.row_values(0)
- elif isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):
- return [col.value for col in sheet.iter_cols(min_row=1, max_row=1)]
- 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, datetime.date)):
- return float(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_name = sheet_names[sheet_index]
- sheet = workbook[sheet_name]
-
- 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]
-
- column_number = column_index + 1
- 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_index]
- 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 小助理,如未能正确解答您的问题,请继续追问。 |
|