鱼C论坛

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

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

[复制链接]
发表于 2024-3-20 09:22:01 | 显示全部楼层
凊风 发表于 2024-03-20 09:21
回复请注意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.     elif cell_format == '数值':
  37.         if isinstance(cell_value, (str, datetime.date)):
  38.             return float(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.    
  48.     while True:
  49.         sheet_names = get_sheet_names(workbook)
  50.         print('请选择要操作的sheet:')
  51.         for i, name in enumerate(sheet_names):
  52.             print(f'{i+1}. {name}')
  53.         
  54.         sheet_index = int(input('请输入选项序号:')) - 1
  55.         sheet_name = sheet_names[sheet_index]
  56.         sheet = workbook[sheet_name]
  57.         
  58.         column_names = get_column_names(sheet)
  59.         print('请选择要转换格式的列:')
  60.         for i, name in enumerate(column_names):
  61.             print(f'{i+1}. {name}')
  62.         
  63.         column_index = int(input('请输入选项序号:')) - 1
  64.         column_name = column_names[column_index]
  65.         
  66.         cell_formats = ['文本', '日期', '数值']
  67.         print('请选择转换后的单元格格式:')
  68.         for i, format in enumerate(cell_formats):
  69.             print(f'{i+1}. {format}')
  70.         
  71.         cell_format_index = int(input('请输入选项序号:')) - 1
  72.         cell_format = cell_formats[cell_format_index]
  73.         
  74.         column_number = column_index + 1
  75.         sheet.insert_cols(column_number + 1)
  76.         
  77.         for row_index, row_values in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
  78.             cell_value = row_values[column_index]
  79.             converted_value = convert_cell_format(cell_value, cell_format)
  80.             sheet.cell(row=row_index, column=column_number + 1, value=converted_value)
  81.         
  82.         workbook.save(file_path)
  83.         print('转换完成!')
  84.         
  85.         choice = input('是否继续转换?(是/否)')
  86.         if choice.lower() != '是':
  87.             break

  88. if __name__ == '__main__':
  89.     main()
复制代码


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

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

使用道具 举报

 楼主| 发表于 2024-3-20 09:23:11 | 显示全部楼层
FishC 发表于 2024-3-20 09:22
非常抱歉,以下是修正后的代码并遵循了Python的语法格式:

报错:
Traceback (most recent call last):
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 101, in <module>
    main()
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 68, in main
    column_names = get_column_names(sheet)
                   ^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 25, in get_column_names
    if isinstance(sheet, xlrd.Sheet):
                         ^^^^^^^^^^
AttributeError: module 'xlrd' has no attribute 'Sheet'. Did you mean: 'sheet'?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:23:33 | 显示全部楼层
凊风 发表于 2024-03-20 09:23
报错:
Traceback (most recent call last):
  File ...


非常抱歉给您带来困扰。根据错误提示,是因为`xlrd`库中没有`Sheet`属性。我修改了代码以解决这个问题,请尝试以下代码:

  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.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.     elif cell_format == '数值':
  37.         if isinstance(cell_value, (str, datetime.date)):
  38.             return float(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.    
  48.     while True:
  49.         sheet_names = get_sheet_names(workbook)
  50.         print('请选择要操作的sheet:')
  51.         for i, name in enumerate(sheet_names):
  52.             print(f'{i+1}. {name}')
  53.         sheet_index = int(input('请输入选项序号:')) - 1
  54.         sheet_name = sheet_names[sheet_index]
  55.         sheet = workbook[sheet_name]
  56.         
  57.         column_names = get_column_names(sheet)
  58.         print('请选择要转换格式的列:')
  59.         for i, name in enumerate(column_names):
  60.             print(f'{i+1}. {name}')
  61.         column_index = int(input('请输入选项序号:')) - 1
  62.         column_name = column_names[column_index]
  63.         
  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('请输入选项序号:')) - 1
  69.         cell_format = cell_formats[cell_format_index]
  70.         
  71.         column_number = column_index + 1
  72.         sheet.insert_cols(column_number + 1)
  73.         
  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_index]
  76.             converted_value = convert_cell_format(cell_value, cell_format)
  77.             sheet.cell(row=row_index, column=column_number + 1, value=converted_value)
  78.         
  79.         workbook.save(file_path)
  80.         print('转换完成!')
  81.         
  82.         choice = input('是否继续转换?(是/否)')
  83.         if choice.lower() != '是':
  84.             break

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


请再次尝试运行,希望这次能够成功。如果还有其他问题,请随时提问。

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

使用道具 举报

 楼主| 发表于 2024-3-20 09:31:48 | 显示全部楼层
FishC 发表于 2024-3-20 09:23
非常抱歉给您带来困扰。根据错误提示,是因为`xlrd`库中没有`Sheet`属性。我修改了代码以解决这个问题 ...

请选择要操作的sheet:
1. Sheet1
请输入选项序号:1
Traceback (most recent call last):
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 101, in <module>
    main()
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 68, in main
    column_names = get_column_names(sheet)
                   ^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 25, in get_column_names
    if isinstance(sheet, xlrd.Sheet):
                         ^^^^^^^^^^
AttributeError: module 'xlrd' has no attribute 'Sheet'. Did you mean: 'sheet'?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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


非常抱歉,我之前的回答中仍然存在错误。根据最新的错误提示,'xlrd'库确实没有`Sheet`属性。我已经修改了代码以解决这个问题,请尝试以下代码: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.Sheet):        return sheet.row_values(0)    elif isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):        return [col[0].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[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        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        sheet.insert_cols(column_index + 2)        for row_index, row in enumerate(sheet.iter_rows(min_row=2), start=2):            cell_value = row[column_index].value            converted_value = convert_cell_format(cell_value, cell_format)            sheet.cell(row=row_index, column=column_index + 2, 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:32:59 | 显示全部楼层
FishC 发表于 2024-3-20 09:32
非常抱歉,我之前的回答中仍然存在错误。根据最新的错误提示,'xlrd'库确实没有`Sheet`属性。我已经修 ...

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

使用道具 举报

发表于 2024-3-20 09:33:14 | 显示全部楼层
凊风 发表于 2024-03-20 09:32
回复请注意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.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.     elif cell_format == '数值':
  37.         if isinstance(cell_value, (str, datetime.date)):
  38.             return float(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.    
  48.     while True:
  49.         sheet_names = get_sheet_names(workbook)
  50.         print('请选择要操作的sheet:')
  51.         for i, name in enumerate(sheet_names):
  52.             print(f'{i+1}. {name}')
  53.         sheet_index = int(input('请输入选项序号:')) - 1
  54.         sheet_name = sheet_names[sheet_index]
  55.         sheet = workbook[sheet_name]
  56.         
  57.         column_names = get_column_names(sheet)
  58.         print('请选择要转换格式的列:')
  59.         for i, name in enumerate(column_names):
  60.             print(f'{i+1}. {name}')
  61.         column_index = int(input('请输入选项序号:')) - 1
  62.         column_name = column_names[column_index]
  63.         
  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('请输入选项序号:')) - 1
  69.         cell_format = cell_formats[cell_format_index]
  70.         
  71.         sheet.insert_cols(column_index + 2)
  72.         
  73.         for row_index, row in enumerate(sheet.iter_rows(min_row=2), start=2):
  74.             cell_value = row[column_index].value
  75.             converted_value = convert_cell_format(cell_value, cell_format)
  76.             sheet.cell(row=row_index, column=column_index + 2, value=converted_value)
  77.         
  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:36:20 | 显示全部楼层
FishC 发表于 2024-3-20 09:33
非常抱歉,下面是修改后的代码,格式已经修正:

请选择要操作的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 67, in main
    column_names = get_column_names(sheet)
                   ^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 28, in get_column_names
    return [col.value for col in sheet.iter_cols(min_row=1, max_row=1)]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 28, in <listcomp>
    return [col.value for col in sheet.iter_cols(min_row=1, max_row=1)]
            ^^^^^^^^^
AttributeError: 'tuple' object has no attribute 'value'
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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


非常抱歉,我在代码中有一个错误。请将以下行的`column_names`的赋值语句更正为:
  1. column_names = [col.value for col in sheet.iter_cols(min_row=1, max_row=1)]
复制代码

这样可以确保在`get_column_names`函数中正确获取所有列名。非常抱歉给您带来困扰,请尝试修改后再次运行代码。如还有其他问题,请随时提问。

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

使用道具 举报

 楼主| 发表于 2024-3-20 09:37:52 | 显示全部楼层
FishC 发表于 2024-3-20 09:36
非常抱歉,我在代码中有一个错误。请将以下行的`column_names`的赋值语句更正为:

这样可以确保在`g ...

在哪里改?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:37:59 | 显示全部楼层


非常抱歉,我之前的回答有误导性。在代码中,您需要更正以下两行:

将:
sheet = workbook[sheet_names]

更正为:
sheet = workbook[sheet_names[sheet_index]]

将:
column_name = column_names

更正为:
column_name = column_names[column_index]

这样可以确保正确获取用户选择的sheet和列。再次对之前的错误回答表示歉意,并感谢您的指正。如还有其他问题,请随时提问。

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

使用道具 举报

 楼主| 发表于 2024-3-20 09:41:13 | 显示全部楼层
FishC 发表于 2024-3-20 09:37
非常抱歉,我之前的回答有误导性。在代码中,您需要更正以下两行:

将:

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

使用道具 举报

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


非常抱歉给您带来困惑。在代码中,我犯了一个错误。

原因在于,当您通过`workbook[sheet_names]`获取要操作的sheet时,返回的是一个元组(tuple),而不是一个具体的sheet对象。

为了解决这个问题,需要将以下代码:

  1. sheet = workbook[sheet_names]
复制代码


更改为:

  1. sheet_name = sheet_names[sheet_index]
  2. sheet = workbook[sheet_name]
复制代码


这样就可以正确获取用户选择的sheet对象了。

对于`get_column_names`函数中的`if isinstance(sheet, xlrd.Sheet)`分支,也需要修改为:

  1. elif isinstance(sheet[0], xlrd.sheet.Sheet):
复制代码


以解决`sheet`是元组的问题。

同时,`column_names`变量也应该修改为:

  1. column_names = get_column_names(sheet[0])
复制代码


这会确保在获取列名时使用正确的sheet对象。

非常抱歉之前的错误,还请您尝试使用修改后的代码。如有其他问题,请随时提问。

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

使用道具 举报

 楼主| 发表于 2024-3-20 09:44:42 | 显示全部楼层
FishC 发表于 2024-3-20 09:41
非常抱歉给您带来困惑。在代码中,我犯了一个错误。

原因在于,当您通过`workbook[sheet_names]`获 ...

全部照这样修改后,报错:

请选择要操作的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 70, in main
    column_names = get_column_names(sheet[0])
                                    ~~~~~^^^
  File "D:\Python\pythonProject\.venv\Lib\site-packages\openpyxl\worksheet\worksheet.py", line 298, in __getitem__
    raise IndexError("{0} is not a valid coordinate or range".format(key))
IndexError: 0 is not a valid coordinate or range
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 09:45:02 | 显示全部楼层
凊风 发表于 2024-03-20 09:44
全部照这样修改后,报错:

请选择要操作的sheet:
...


非常抱歉让您遇到了这个问题。根据错误提示,问题出现在`worksheet.py`文件的第298行,指示索引错误。这表明在获取列名时出现了问题。经过检查,发现在`get_column_names`函数中,对于`openpyxl`库的`sheet`对象的处理有误。具体来说,将以下代码:
  1. elif isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):
  2.     return [col.value for col in sheet.iter_cols(min_row=1, max_row=1)]
复制代码

修改为:
  1. elif isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):
  2.     return [col[0].value for col in sheet.iter_cols(min_row=1, max_row=1)]
复制代码

这样修改后,将正确获取列名信息。非常抱歉之前的错误和困惑,希望这次修改能够解决问题。如果还有其他疑问,请随时提问。

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

使用道具 举报

 楼主| 发表于 2024-3-20 09:47:18 | 显示全部楼层
FishC 发表于 2024-3-20 09:45
非常抱歉让您遇到了这个问题。根据错误提示,问题出现在`worksheet.py`文件的第298行,指示索引错误。 ...

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

请输入选项序号:3
请选择转换后的单元格格式:
1. 文本
2. 日期
3. 数值
请输入选项序号:3
Traceback (most recent call last):
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 101, in <module>
    main()
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 90, in main
    converted_value = convert_cell_format(cell_value, cell_format)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 48, in convert_cell_format
    if isinstance(cell_value, (str, datetime.date)):
                                    ^^^^^^^^
NameError: name 'datetime' is not defined
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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


非常抱歉给您带来困扰。根据错误提示,代码在使用`datetime`模块时出现了命名错误。为了解决这个问题,我们需要在代码的开头处导入`datetime`模块。请将以下代码添加到代码开头:import datetime这样修改之后,代码应该能够正确地执行了。如果还有其他问题,请随时提问。谢谢!

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

使用道具 举报

 楼主| 发表于 2024-3-20 09:50:32 | 显示全部楼层
FishC 发表于 2024-3-20 09:47
非常抱歉给您带来困扰。根据错误提示,代码在使用`datetime`模块时出现了命名错误。为了解决这个问题, ...

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


请输入选项序号:3
请选择转换后的单元格格式:
1. 文本
2. 日期
3. 数值
请输入选项序号:3
Traceback (most recent call last):
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 102, in <module>
    main()
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 91, in main
    converted_value = convert_cell_format(cell_value, cell_format)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Python\pythonProject\Xtt_xls\cell_format_change.py", line 50, in convert_cell_format
    return float(cell_value)
           ^^^^^^^^^^^^^^^^^
ValueError: could not convert string to float: '5324014001X'

对原本已经是数值型的单元格,应该继续向下判断和转换,而不应该报错。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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


非常抱歉给您带来困扰。根据错误提示,代码在尝试将非浮点数字符串转换为浮点数时出现了错误。为了解决这个问题,我们可以修改`convert_cell_format`函数,对于已经是数值类型的单元格,直接返回原始值而不进行转换。请将以下代码替换`convert_cell_format`函数的内容:

  1. def convert_cell_format(cell_value, cell_format):
  2.     # 根据用户指定的格式进行转换,这里只演示了两种常见的格式
  3.     if cell_format == '文本':
  4.         if isinstance(cell_value, (int, float, str)):
  5.             return str(cell_value)
  6.         else:
  7.             return cell_value
  8.     elif cell_format == '日期':
  9.         if isinstance(cell_value, str):
  10.             return datetime.datetime.strptime(cell_value, '%Y-%m-%d').date()
  11.         else:
  12.             return cell_value
  13.     elif cell_format == '数值':
  14.         if isinstance(cell_value, (int, float)):
  15.             return cell_value
  16.         elif isinstance(cell_value, str) and cell_value.isnumeric():
  17.             return float(cell_value)
  18.         else:
  19.             return cell_value
  20.     else:
  21.         return cell_value
复制代码


这样修改之后,对于已经是数值型的单元格,程序将继续向下判断和转换,并将其作为浮点数保存。如果还有其他问题,请随时提问。谢谢!

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

使用道具 举报

 楼主| 发表于 2024-3-20 09:54:14 | 显示全部楼层
FishC 发表于 2024-3-20 09:50
非常抱歉给您带来困扰。根据错误提示,代码在尝试将非浮点数字符串转换为浮点数时出现了错误。为了解决 ...

身份证号(文本型)转换为”数值型”后,不要用科学计数法,并且后4位不应该全部变为0。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-27 23:01

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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