|
发表于 2024-3-20 08:49:54
|
显示全部楼层
非常抱歉,我之前的回答中有一个错误。在 `sheet.iter_rows()` 返回的是一个字符串列表,而不是一个具有 `row` 属性的对象。因此,在这里需要使用索引来访问行号。请将以下代码进行修改:
- 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] # 列索引从1开始,故需减1
- converted_value = convert_cell_format(cell_value, cell_format)
- sheet.cell(row=row_index, column=column_number + 2, value=converted_value)
复制代码
修复后的代码应该如下所示:
- 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_letters = list(sheet.columns)
- column_names = [col_letters[0].column_letter for col_letters 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) # 在指定列后插入一列
- 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] # 列索引从1开始,故需减1
- converted_value = convert_cell_format(cell_value, cell_format)
- sheet.cell(row=row_index, column=column_number + 2, value=converted_value)
- workbook.save(file_path)
- choice = input('是否继续转换?(是/否)')
- if choice.lower() != '是':
- break
- if __name__ == '__main__':
- main()
复制代码
非常抱歉给您带来了困扰,希望这次修改能解决问题。如果还有任何疑问,请随时提出。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|