抱歉,我在回答中的代码格式有些混乱。以下是修正后格式化的代码示例:
import xlrd
import openpyxl
import datetime
import xlsxwriter
from openpyxl.styles import numbers
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)
def get_sheet_names(workbook):
if isinstance(workbook, xlrd.Book):
return workbook.sheet_names()
elif isinstance(workbook, openpyxl.Workbook):
return workbook.sheetnames
def get_column_names(sheet):
if isinstance(sheet, xlrd.Sheet):
return sheet.row_values(0)
elif isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):
return [cell.value for cell in sheet]
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, (int, float)):
return cell_value
elif isinstance(cell_value, str) and cell_value.isnumeric():
if len(cell_value) < 15:
return float(cell_value)
else:
return cell_value
else:
return cell_value
else:
return cell_value
def main():
file_path = input('请输入工作簿路径:')
file_suffix = input('请输入工作簿的后缀(xls或xlsx):')
workbook = open_workbook(file_path)
while True:
sheet_names = get_sheet_names(workbook)
for i, name in enumerate(sheet_names):
print(f'{i+1}. {name}')
sheet_index = int(input('请选择要操作的sheet序号:')) - 1
sheet = workbook[sheet_index]
column_names = get_column_names(sheet)
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]
new_workbook = xlsxwriter.Workbook('converted_workbook.xlsx')
new_sheet = new_workbook.add_worksheet()
format_mapping = {'文本': new_workbook.add_format(),
'日期': new_workbook.add_format({'num_format': 'yyyy-mm-dd'}),
'数值': new_workbook.add_format({'num_format': '0'})}
converted_format = format_mapping[cell_format]
for row_index, row in enumerate(sheet.iter_rows(min_row=1), start=1):
for col_index, cell in enumerate(row):
if row_index == 1:
new_sheet.write(row_index-1, col_index, cell.value, converted_format)
else:
converted_value = convert_cell_format(cell.value, cell_format)
new_sheet.write(row_index-1, col_index, converted_value, converted_format)
new_workbook.close()
choice = input('是否继续转换?(是/否)')
if choice.lower() != '是':
break
if __name__ == '__main__':
main()
这个版本已经修复了代码格式的问题,现在应该可以正确运行并实现所需的功能了。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |