鱼C论坛

 找回密码
 立即注册
楼主: 凊风

单元格格式转换求教2~~

[复制链接]
发表于 2024-3-20 09:02:22 | 显示全部楼层
凊风 发表于 2024-03-20 09:02
回复请注意python格式


非常抱歉,这是修订后的代码,按照Python格式进行了调整:

  1. import openpyxl
  2. from tkinter import Tk, filedialog
  3. from tkinter import ttk
  4. import datetime

  5. def open_workbook(file_path):
  6.     if file_path.endswith('.xlsx'):
  7.         return openpyxl.load_workbook(file_path)
  8.     else:
  9.         raise ValueError('Invalid file format')

  10. def get_sheet_names(workbook):
  11.     if isinstance(workbook, openpyxl.Workbook):
  12.         return workbook.sheetnames
  13.     else:
  14.         raise ValueError('Invalid workbook type')

  15. def get_column_names(sheet):
  16.     if isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):
  17.         column_letters = list(sheet.columns)
  18.         column_names =  [column_letter[0].value for column_letter in column_letters]
  19.         return column_names
  20.     else:
  21.         raise ValueError('Invalid sheet type')

  22. def convert_cell_format(cell_value, cell_format):
  23.     if cell_format == '文本':
  24.         if isinstance(cell_value, (int, float)):
  25.             return str(cell_value)
  26.         else:
  27.             return cell_value
  28.     elif cell_format == '日期':
  29.         if isinstance(cell_value, str):
  30.             return datetime.datetime.strptime(cell_value, '%Y-%m-%d').date()
  31.         else:
  32.             return cell_value
  33.     elif cell_format == '数值':
  34.         if isinstance(cell_value, str):
  35.             return cell_value
  36.         else:
  37.             return str(cell_value)
  38.     else:
  39.         return cell_value

  40. def main():
  41.     root = Tk()
  42.     root.withdraw()
  43.     file_path = filedialog.askopenfilename(title='选择工作簿', filetypes=(('Excel files', '*.xlsx'),))
  44.     root.destroy()
  45.     workbook = open_workbook(file_path)
  46.     while True:
  47.         sheet_names = get_sheet_names(workbook)
  48.         print('请选择要操作的sheet:')
  49.         for i, name in enumerate(sheet_names):
  50.             print(f'{i+1}. {name}')
  51.         sheet_index = int(input('请输入选项序号:')) - 1
  52.         sheet = workbook[sheet_names[sheet_index]]
  53.         column_names = get_column_names(sheet)
  54.         print('请选择要转换格式的列:')
  55.         for i, name in enumerate(column_names):
  56.             column_letter = openpyxl.utils.get_column_letter(i + 1)
  57.             print(f'{column_letter}. {name}')
  58.         column_index = input('请输入选项序号:')
  59.         if not column_index.isdigit() or int(column_index) not in range(1, len(column_names) + 1):
  60.             print('无效的选项序号,请重新输入')
  61.             continue
  62.         column_name = column_names[int(column_index) - 1]
  63.         cell_formats = ["文本", "日期", "数值"]
  64.         print('请选择转换后的单元格格式:')
  65.         for i, format in enumerate(cell_formats):
  66.             print(f'{i+1}. {format}')
  67.         cell_format_index = int(input('请输入选项序号:'))
  68.         if cell_format_index not in range(1, len(cell_formats)+1):
  69.             print('无效的选项序号,请重新输入')
  70.             continue
  71.         cell_format = cell_formats[cell_format_index - 1]
  72.         column_number = openpyxl.utils.column_index_from_string(column_name)
  73.         sheet.insert_cols(column_number + 2) # 在指定列后插入一列
  74.         for row_index, row_values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
  75.             cell_value = row_values[column_number - 1]
  76.             converted_value = convert_cell_format(cell_value, cell_format)
  77.             sheet.cell(row=row_index, column=column_number + 2, value=converted_value)
  78.         workbook.save(file_path)
  79.         print('转换完成!')
  80.         choice = input('是否继续转换?(是/否)')
  81.         if choice.lower() != '是':
  82.             break

  83. if __name__ == '__main__':
  84.     main()
复制代码


希望此格式更符合您的需求。如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-20 09:04:31 | 显示全部楼层
FishC 发表于 2024-3-20 09:02
非常抱歉,这是修订后的代码,按照Python格式进行了调整:

请选择要转换格式的列:
A. 单位名
B. 姓名
C. 身份证号码
D. 补发数
E. 补发月份
F. 执行时间
G. 备注

请输入选项序号:C
无效的选项序号,请重新输入

选C报错!!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:05:09 | 显示全部楼层
凊风 发表于 2024-03-20 09:04
请选择要转换格式的列:
A. 单位名
B. 姓名
C. 身 ...


非常抱歉,给您带来困惑。我发现了代码中的一个错误,导致无法正确识别列的索引。以下是已经更正的代码:import openpyxlfrom tkinter import Tk, filedialogfrom tkinter import ttkimport datetimedef 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].value 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):            return cell_value        else:            return str(cell_value)    else:        return cell_valuedef 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]        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        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            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)        print('转换完成!')        choice = input('是否继续转换?(是/否)')        if choice.lower() != '是':            breakif __name__ == '__main__':    main()请使用字母选项序号来选择要转换格式的列,例如选择C列应输入"C"。非常抱歉给您带来了困惑,希望这次修改解决了问题。如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-20 09:05:40 | 显示全部楼层
FishC 发表于 2024-3-20 09:05
非常抱歉,给您带来困惑。我发现了代码中的一个错误,导致无法正确识别列的索引。以下是已经更正的代码 ...

回复请注意pyton格式
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:06:10 | 显示全部楼层
凊风 发表于 2024-03-20 09:05
回复请注意pyton格式


非常抱歉,在回答中的某些代码块中确实存在缩进错误。以下是修复了缩进错误的Python代码:

  1. import openpyxl
  2. from tkinter import Tk, filedialog
  3. from tkinter import ttk
  4. import datetime

  5. def open_workbook(file_path):
  6.     if file_path.endswith('.xlsx'):
  7.         return openpyxl.load_workbook(file_path)
  8.     else:
  9.         raise ValueError('Invalid file format')

  10. def get_sheet_names(workbook):
  11.     if isinstance(workbook, openpyxl.Workbook):
  12.         return workbook.sheetnames
  13.     else:
  14.         raise ValueError('Invalid workbook type')

  15. def get_column_names(sheet):
  16.     if isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):
  17.         column_letters = list(sheet.columns)
  18.         column_names =  [column_letter.value for column_letter in column_letters]
  19.         return column_names
  20.     else:
  21.         raise ValueError('Invalid sheet type')

  22. def convert_cell_format(cell_value, cell_format):
  23.     if cell_format == '文本':
  24.         if isinstance(cell_value, (int, float)):
  25.             return str(cell_value)
  26.         else:
  27.             return cell_value
  28.     elif cell_format == '日期':
  29.         if isinstance(cell_value, str):
  30.             return datetime.datetime.strptime(cell_value, '%Y-%m-%d').date()
  31.         else:
  32.             return cell_value
  33.     elif cell_format == '数值':
  34.         if isinstance(cell_value, str):
  35.             return cell_value
  36.         else:
  37.             return str(cell_value)
  38.     else:
  39.         return cell_value

  40. def main():
  41.     root = Tk()
  42.     root.withdraw()
  43.     file_path = filedialog.askopenfilename(title='选择工作簿', filetypes=(('Excel files', '*.xlsx'),))
  44.     root.destroy()
  45.     workbook = open_workbook(file_path)
  46.     while True:
  47.         sheet_names = get_sheet_names(workbook)
  48.         print('请选择要操作的sheet:')
  49.         for i, name in enumerate(sheet_names):
  50.             print(f'{i+1}. {name}')
  51.         sheet_index = int(input('请输入选项序号:')) - 1
  52.         sheet = workbook[sheet_names[sheet_index]]
  53.         column_names = get_column_names(sheet)
  54.         print('请选择要转换格式的列:')
  55.         for i, name in enumerate(column_names):
  56.             column_letter = openpyxl.utils.get_column_letter(i + 1)
  57.             print(f'{column_letter}. {name}')
  58.         column_index = input('请输入选项序号:')
  59.         if not column_index.isalpha() or column_index.lower() not in column_names:
  60.             print('无效的选项序号,请重新输入')
  61.             continue
  62.         column_name = column_index.upper()
  63.         cell_formats = ['文本', '日期', '数值']
  64.         print('请选择转换后的单元格格式:')
  65.         for i, format in enumerate(cell_formats):
  66.             print(f'{i+1}. {format}')
  67.         cell_format_index = int(input('请输入选项序号:'))
  68.         if cell_format_index not in range(1, len(cell_formats)+1):
  69.             print('无效的选项序号,请重新输入')
  70.             continue
  71.         cell_format = cell_formats[cell_format_index-1]
  72.         column_number = openpyxl.utils.column_index_from_string(column_name)
  73.         sheet.insert_cols(column_number + 1) # 在指定列后插入一列
  74.         for row_index, row_values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
  75.             cell_value = row_values[column_number-1]
  76.             converted_value = convert_cell_format(cell_value, cell_format)
  77.             sheet.cell(row=row_index, column=column_number + 1, value=converted_value)
  78.         workbook.save(file_path)
  79.         print('转换完成!')
  80.         choice = input('是否继续转换?(是/否)')
  81.         if choice.lower() != '是':
  82.             break

  83. if __name__ == '__main__':
  84.     main()
复制代码


非常抱歉给您带来的困扰,现在代码应该没有问题了。如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-20 09:07:06 | 显示全部楼层
FishC 发表于 2024-3-20 09:06
非常抱歉,在回答中的某些代码块中确实存在缩进错误。以下是修复了缩进错误的Python代码:

报错:

请选择要操作的sheet:
1. Sheet1
请输入选项序号:1
Traceback (most recent call last):
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 96, in <module>
    main()
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 63, in main
    column_names = get_column_names(sheet)
                   ^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 24, in get_column_names
    column_names = [column_letter.value for column_letter in column_letters]
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 24, in <listcomp>
    column_names = [column_letter.value for column_letter in column_letters]
                    ^^^^^^^^^^^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'value'
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:07:27 | 显示全部楼层
凊风 发表于 2024-03-20 09:07
报错:

请选择要操作的sheet:
1. Sheet1
请输入 ...


非常抱歉给您带来困扰。根据报错信息,我们可以看出在`get_column_names`函数中出现了错误。根据当前代码的逻辑,当`sheet`为`openpyxl`库返回的`Worksheet`对象时,应该使用`iter_cols()`方法来获取列名。下面是修正后的代码:import openpyxlfrom tkinter import Tk, filedialogfrom tkinter import ttkimport datetimedef 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_valuedef 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]        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        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            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() != '是':            breakif __name__ == '__main__':    main()请尝试运行修正后的代码,如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-20 09:07:50 | 显示全部楼层
FishC 发表于 2024-3-20 09:07
非常抱歉给您带来困扰。根据报错信息,我们可以看出在`get_column_names`函数中出现了错误。根据当前代 ...

回复请注意python格式
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:08:09 | 显示全部楼层
凊风 发表于 2024-03-20 09:07
回复请注意python格式


非常抱歉,下面是修正后的代码(使用了正确的Python格式):

  1. import openpyxl
  2. from tkinter import Tk, filedialog
  3. from tkinter import ttk
  4. import datetime

  5. def open_workbook(file_path):
  6.     if file_path.endswith('.xlsx'):
  7.         return openpyxl.load_workbook(file_path)
  8.     else:
  9.         raise ValueError('Invalid file format')

  10. def get_sheet_names(workbook):
  11.     if isinstance(workbook, openpyxl.Workbook):
  12.         return workbook.sheetnames
  13.     else:
  14.         raise ValueError('Invalid workbook type')

  15. def get_column_names(sheet):
  16.     if isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):
  17.         column_names = []
  18.         for col in sheet.iter_cols(min_row=1, max_row=1, values_only=True):
  19.             column_names.extend(col)
  20.         return column_names
  21.     else:
  22.         raise ValueError('Invalid sheet type')

  23. def convert_cell_format(cell_value, cell_format):
  24.     if cell_format == '文本':
  25.         if isinstance(cell_value, (int, float)):
  26.             return str(cell_value)
  27.         else:
  28.             return cell_value
  29.     elif cell_format == '日期':
  30.         if isinstance(cell_value, str):
  31.             return datetime.datetime.strptime(cell_value, '%Y-%m-%d').date()
  32.         else:
  33.             return cell_value
  34.     elif cell_format == '数值':
  35.         if isinstance(cell_value, str):
  36.             return cell_value
  37.         else:
  38.             return str(cell_value)
  39.     else:
  40.         return cell_value

  41. def main():
  42.     root = Tk()
  43.     root.withdraw()
  44.     file_path = filedialog.askopenfilename(title='选择工作簿', filetypes=(('Excel files', '*.xlsx'),))
  45.     root.destroy()
  46.     workbook = open_workbook(file_path)
  47.     while True:
  48.         sheet_names = get_sheet_names(workbook)
  49.         print('请选择要操作的sheet:')
  50.         for i, name in enumerate(sheet_names):
  51.             print(f'{i+1}. {name}')
  52.         sheet_index = int(input('请输入选项序号:')) - 1
  53.         sheet = workbook[sheet_names[sheet_index]]
  54.         column_names = get_column_names(sheet)
  55.         print('请选择要转换格式的列:')
  56.         for i, name in enumerate(column_names):
  57.             column_letter = openpyxl.utils.get_column_letter(i + 1)
  58.             print(f'{column_letter}. {name}')
  59.         column_index = input('请输入选项序号:')
  60.         if not column_index.isalpha() or column_index.lower() not in column_names:
  61.             print('无效的选项序号,请重新输入')
  62.             continue
  63.         column_name = column_index.upper()
  64.         cell_formats = ['文本', '日期', '数值']
  65.         print('请选择转换后的单元格格式:')
  66.         for i, format in enumerate(cell_formats):
  67.             print(f'{i+1}. {format}')
  68.         cell_format_index = int(input('请输入选项序号:'))
  69.         if cell_format_index not in range(1, len(cell_formats)+1):
  70.             print('无效的选项序号,请重新输入')
  71.             continue
  72.         cell_format = cell_formats[cell_format_index-1]
  73.         column_number = openpyxl.utils.column_index_from_string(column_name)
  74.         sheet.insert_cols(column_number + 1) # 在指定列后插入一列
  75.         for row_index, row_values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
  76.             cell_value = row_values[column_number-1]
  77.             converted_value = convert_cell_format(cell_value, cell_format)
  78.             sheet.cell(row=row_index, column=column_number + 1, value=converted_value)
  79.         workbook.save(file_path)
  80.         print('转换完成!')
  81.         choice = input('是否继续转换?(是/否)')
  82.         if choice.lower() != '是':
  83.             break

  84. if __name__ == '__main__':
  85.     main()
复制代码


非常抱歉给您带来的困扰,请尝试使用修正后的代码运行。如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-20 09:09:36 | 显示全部楼层
FishC 发表于 2024-3-20 09:08
非常抱歉,下面是修正后的代码(使用了正确的Python格式):

请选择要操作的sheet:
1. Sheet1
请输入选项序号:1
请选择要转换格式的列:
A. 单位名
B. 姓名
C. 身份证号码


请输入选项序号:C
无效的选项序号,请重新输入

选C报错!!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:09:52 | 显示全部楼层
凊风 发表于 2024-03-20 09:09
请选择要操作的sheet:
1. Sheet1
请输入选项序号: ...


非常抱歉给您带来的困扰,代码中对于列名的输入存在一点误解。以下是修正后可以正确选择列名的代码:

  1. def main():
  2.     root = Tk()
  3.     root.withdraw()
  4.     file_path = filedialog.askopenfilename(title='选择工作簿', filetypes=(('Excel files', '*.xlsx'),))
  5.     root.destroy()
  6.     workbook = open_workbook(file_path)
  7.     while True:
  8.         sheet_names = get_sheet_names(workbook)
  9.         print('请选择要操作的sheet:')
  10.         for i, name in enumerate(sheet_names):
  11.             print(f'{i+1}. {name}')
  12.         sheet_index = int(input('请输入选项序号:')) - 1
  13.         sheet = workbook[sheet_names[sheet_index]]
  14.         
  15.         column_names = get_column_names(sheet)
  16.         print('请选择要转换格式的列:')
  17.         for i, name in enumerate(column_names):
  18.             print(f'{openpyxl.utils.get_column_letter(i+1)}. {name}')
  19.         column_index = input('请输入选项序号(例如A、B、C):')
  20.         if not column_index.isalpha() or column_index.upper() not in openpyxl.utils.column_index_from_string(column_index):
  21.             print('无效的选项序号,请重新输入')
  22.             continue
  23.         column_name = column_index.upper()

  24.         cell_formats = ['文本', '日期', '数值']
  25.         print('请选择转换后的单元格格式:')
  26.         for i, format in enumerate(cell_formats):
  27.             print(f'{i+1}. {format}')
  28.         cell_format_index = int(input('请输入选项序号:'))
  29.         if cell_format_index not in range(1, len(cell_formats)+1):
  30.             print('无效的选项序号,请重新输入')
  31.             continue
  32.         cell_format = cell_formats[cell_format_index - 1]

  33.         column_number = openpyxl.utils.column_letter(column_name)
  34.         sheet.insert_cols(column_number + 1) # 在指定列后插入一列

  35.         for row_index, row_values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
  36.             cell_value = row_values[column_number - 1]
  37.             converted_value = convert_cell_format(cell_value, cell_format)
  38.             sheet.cell(row=row_index, column=column_number + 1, value=converted_value)

  39.         workbook.save(file_path)
  40.         print('转换完成!')

  41.         choice = input('是否继续转换?(是/否)')
  42.         if choice.lower() != '是':
  43.             break

  44. if __name__ == '__main__':
  45.     main()
复制代码


修正后的代码中,改变了对于列名的处理方法,可以通过输入字母来选择要转换格式的列。感谢您的耐心和理解,如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-20 09:12:18 | 显示全部楼层
FishC 发表于 2024-3-20 09:09
非常抱歉给您带来的困扰,代码中对于列名的输入存在一点误解。以下是修正后可以正确选择列名的代码:
...

报错:
请选择要操作的sheet:
1. Sheet1
请输入选项序号:1
请选择要转换格式的列:
A. 单位名
B. 姓名
C. 身份证号码

请输入选项序号(例如A、B、C):C
Traceback (most recent call last):
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 103, in <module>
    main()
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 70, in main
    if not column_index.isalpha() or column_index.upper() not in openpyxl.utils.column_index_from_string(
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: argument of type 'int' is not iterable
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:12:34 | 显示全部楼层
凊风 发表于 2024-03-20 09:12
报错:
请选择要操作的sheet:
1. Sheet1
请输入选 ...


非常抱歉给您带来困扰,这是因为代码中对于列名的处理有误。以下是修正后的代码:

  1. def main():
  2.     root = Tk()
  3.     root.withdraw()
  4.     file_path = filedialog.askopenfilename(title='选择工作簿', filetypes=(('Excel files', '*.xlsx'),))
  5.     root.destroy()
  6.     workbook = open_workbook(file_path)
  7.     while True:
  8.         sheet_names = get_sheet_names(workbook)
  9.         print('请选择要操作的sheet:')
  10.         for i, name in enumerate(sheet_names):
  11.             print(f'{i+1}. {name}')
  12.         sheet_index = int(input('请输入选项序号:')) - 1
  13.         sheet = workbook[sheet_names]

  14.         column_names = get_column_names(sheet)
  15.         print('请选择要转换格式的列:')
  16.         for i, name in enumerate(column_names):
  17.             print(f'{openpyxl.utils.get_column_letter(i+1)}. {name}')
  18.         column_index = input('请输入选项序号(例如A、B、C):')
  19.         if not column_index.isalpha() or openpyxl.utils.column_index_from_string(column_index.upper()):
  20.             print('无效的选项序号,请重新输入')
  21.             continue
  22.         column_name = openpyxl.utils.column_index_from_string(column_index.upper())

  23.         cell_formats = ['文本', '日期']
  24.         print('请选择转换后的单元格格式:')
  25.         for i, format in enumerate(cell_formats):
  26.             print(f'{i+1}. {format}')
  27.         cell_format_index = int(input('请输入选项序号:'))
  28.         if cell_format_index not in range(1, len(cell_formats)+1):
  29.             print('无效的选项序号,请重新输入')
  30.             continue
  31.         cell_format = cell_formats[cell_format_index-1]

  32.         column_number = column_name
  33.         sheet.insert_cols(column_number + 1) # 在指定列后插入一列
  34.         for row_index, row_values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
  35.             cell_value = row_values[column_number-1]
  36.             converted_value = convert_cell_format(cell_value, cell_format)
  37.             sheet.cell(row=row_index, column=column_number + 1, value=converted_value)
  38.         workbook.save(file_path)
  39.         print('转换完成!')
  40.         choice = input('是否继续转换?(是/否)')
  41.         if choice.lower() != '是':
  42.             break

  43. if __name__ == '__main__':
  44.     main()
复制代码


修正后的代码中,对于输入的列索引会使用`openpyxl.utils.column_index_from_string()`函数将字母转换为对应的数字表示。请尝试使用修正后的代码,并再次检查是否出现问题。如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-20 09:13:55 | 显示全部楼层
FishC 发表于 2024-3-20 09:12
非常抱歉给您带来困扰,这是因为代码中对于列名的处理有误。以下是修正后的代码:

请选择要操作的sheet:
1. Sheet1
请输入选项序号:1
Traceback (most recent call last):
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 99, in <module>
    main()
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 63, in main
    sheet = workbook[sheet_names]
            ~~~~~~~~^^^^^^^^^^^^^
  File "D:\Python\pythonProject\.venv\Lib\site-packages\openpyxl\workbook\workbook.py", line 287, in __getitem__
    raise KeyError("Worksheet {0} does not exist.".format(key))
KeyError: "Worksheet ['Sheet1'] does not exist."
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:14:35 | 显示全部楼层
凊风 发表于 2024-03-20 09:13
请选择要操作的sheet:
1. Sheet1
请输入选项序号: ...


非常抱歉给您带来困扰,这是因为代码中获取sheet的方式有误。请使用以下修正后的代码: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 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'{openpyxl.utils.get_column_letter(i+1)}. {name}')        column_index = input('请输入选项序号(例如A、B、C):')        if not column_index.isalpha() or openpyxl.utils.column_index_from_string(column_index.upper()):            print('无效的选项序号,请重新输入')            continue        column_name = openpyxl.utils.column_index_from_string(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        column_number = 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            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() != '是':            breakif __name__ == '__main__':    main()请使用修正后的代码,并再次尝试运行。如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-20 09:15:33 | 显示全部楼层
FishC 发表于 2024-3-20 09:14
非常抱歉给您带来困扰,这是因为代码中获取sheet的方式有误。请使用以下修正后的代码:def get_sheet_n ...

回复请注意python格式
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:15:50 | 显示全部楼层
凊风 发表于 2024-03-20 09:15
回复请注意python格式


非常抱歉,以下是修正后的带有正确Python格式的代码:

  1. import openpyxl
  2. import xlrd
  3. from tkinter import Tk, filedialog

  4. def open_workbook(file_path):
  5.     if file_path.endswith('.xls'):
  6.         return xlrd.open_workbook(file_path)
  7.     elif file_path.endswith('.xlsx'):
  8.         return openpyxl.load_workbook(file_path)
  9.     else:
  10.         raise ValueError('Invalid file format')

  11. def get_sheet_names(workbook):
  12.     if isinstance(workbook, xlrd.Book):
  13.         return workbook.sheet_names()
  14.     elif isinstance(workbook, openpyxl.Workbook):
  15.         return workbook.sheetnames
  16.     else:
  17.         raise ValueError('Invalid workbook type')

  18. def get_column_names(sheet):
  19.     if isinstance(sheet, xlrd.Sheet):
  20.         return sheet.row_values(0)
  21.     elif isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):
  22.         return [col.value for col in sheet.iter_cols(min_row=1, max_row=1)]
  23.     else:
  24.         raise ValueError('Invalid sheet type')

  25. def convert_cell_format(cell_value, cell_format):
  26.     if cell_format == '文本':
  27.         if isinstance(cell_value, (int, float)):
  28.             return str(cell_value)
  29.         else:
  30.             return cell_value
  31.     elif cell_format == '日期':
  32.         if isinstance(cell_value, str):
  33.             return datetime.datetime.strptime(cell_value, '%Y-%m-%d').date()
  34.         else:
  35.             return cell_value
  36.     else:
  37.         return cell_value

  38. def main():
  39.     root = Tk()
  40.     root.withdraw()
  41.     file_path = filedialog.askopenfilename(title='选择工作簿', filetypes=(('Excel files', '*.xlsx'),))
  42.     root.destroy()
  43.     workbook = open_workbook(file_path)
  44.    
  45.     while True:
  46.         sheet_names = get_sheet_names(workbook)
  47.         print('请选择要操作的sheet:')
  48.         for i, name in enumerate(sheet_names):
  49.             print(f'{i+1}. {name}')
  50.         sheet_index = int(input('请输入选项序号:')) - 1
  51.         sheet_name = sheet_names[sheet_index]
  52.         sheet = workbook[sheet_name]
  53.         
  54.         column_names = get_column_names(sheet)
  55.         print('请选择要转换格式的列:')
  56.         for i, name in enumerate(column_names):
  57.             print(f'{i+1}. {name}')
  58.         column_index = int(input('请输入选项序号:')) - 1
  59.         column_name = column_names[column_index]
  60.         
  61.         cell_formats = ['文本', '日期']
  62.         print('请选择转换后的单元格格式:')
  63.         for i, format in enumerate(cell_formats):
  64.             print(f'{i+1}. {format}')
  65.         cell_format_index = int(input('请输入选项序号:')) - 1
  66.         cell_format = cell_formats[cell_format_index]
  67.         
  68.         column_number = column_index + 1
  69.         sheet.insert_cols(column_number + 1)  # 在指定列后插入一列
  70.         
  71.         for row_index, row_values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
  72.             cell_value = row_values[column_index]
  73.             converted_value = convert_cell_format(cell_value, cell_format)
  74.             sheet.cell(row=row_index, column=column_number + 1, value=converted_value)
  75.         
  76.         workbook.save(file_path)
  77.         print('转换完成!')
  78.         
  79.         choice = input('是否继续转换?(是/否)')
  80.         if choice.lower() != '是':
  81.             break

  82. if __name__ == '__main__':
  83.     main()
复制代码


请使用这段修正后的代码,并尝试运行。如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-20 09:17:38 | 显示全部楼层
FishC 发表于 2024-3-20 09:15
非常抱歉,以下是修正后的带有正确Python格式的代码:

这次差了转换后的单元格格式选项        ”数值“。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:18:05 | 显示全部楼层
凊风 发表于 2024-03-20 09:17
这次差了转换后的单元格格式选项        ”数值“。


非常抱歉,我遗漏了"数值"选项。以下是添加了该选项的修正代码:import openpyxlimport xlrdfrom tkinter import Tk, filedialogdef 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):        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_valuedef 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 = workbook                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                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                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            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() != '是':            breakif __name__ == '__main__':    main()非常抱歉再次遗漏"数值"选项,在修正的代码中已经添加了该选项。请使用这段修正后的代码,并尝试运行。如果还有其他问题,请随时提问。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-3-20 09:21:41 | 显示全部楼层
FishC 发表于 2024-3-20 09:18
非常抱歉,我遗漏了"数值"选项。以下是添加了该选项的修正代码:import openpyxlimport xlrdfrom tkint ...

回复请注意python格式
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 05:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表