鱼C论坛

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

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

[复制链接]
发表于 2024-3-20 10:23:37 | 显示全部楼层
凊风 发表于 2024-03-20 10:23
为什么身份证号(18位文本型)转换后还是文本型呢?


身份证号码通常以文本形式存储,因为它们不仅仅是数字。一个身份证号码可能包含字母、数字和特殊字符,例如X或者*。此外,身份证号码还具有特殊的格式要求,例如前面的地区代码、生日等信息。

在给定的转换函数中,并没有对身份证号码进行特殊处理,而只是简单地将值转换为浮点数格式。这样做的目的是确保转换函数返回的结果是数值类型(float),方便进行数值计算和比较。

如果您想要将身份证号码转换为整数或字符串格式,可以根据具体需求修改转换函数。例如,如果您希望保留身份证号码的文本格式,可以将返回语句改为 `return str(cell_value)`。

请注意,身份证号码是一个特殊的标识符,具体的处理方式可能因国家或地区而异。因此,在实际应用中,建议根据实际需求进行适当的处理和验证。

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

使用道具 举报

 楼主| 发表于 2024-3-20 10:42:36 | 显示全部楼层
凊风 发表于 2024-3-20 10:23
为什么身份证号(18位文本型)转换后还是文本型呢?

请问能不能通过保留原单元格value然后设置此单元格格式的方法以来实现呢?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 10:42:47 | 显示全部楼层
凊风 发表于 2024-03-20 10:42
请问能不能通过保留原单元格value然后设置此单元格格 ...


是的,您可以通过设置单元格的格式来实现保留原单元格值并更改其格式的效果。使用`openpyxl`库可以实现这一点。

首先,您需要使用`openpyxl.styles`模块中的`NumberFormat`对象来定义您想要设置的格式。然后,将此格式应用于所需的单元格。以下是一个示例代码:import openpyxlfrom openpyxl import stylesfrom openpyxl.styles import Numb

请注意,根据具体的格式需求,您需要自行调整`NumberFormat`的参数,确保符合您的期望。

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

使用道具 举报

 楼主| 发表于 2024-3-20 10:46:24 | 显示全部楼层
FishC 发表于 2024-3-20 10:42
是的,您可以通过设置单元格的格式来实现保留原单元格值并更改其格式的效果。使用`openpyxl`库可以实现 ...

能否在本贴第九十六楼的基础上加入此功能呢?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 10:46:57 | 显示全部楼层
凊风 发表于 2024-03-20 10:46
能否在本贴第九十六楼的基础上加入此功能呢?


当然可以,请看下面的代码:import openpyxlfrom openpyxl import stylesfrom openpyxl.styles import NumberFormatdef open_workbook(file_path):    if file_path.endswith('.xls'):        # 使用xlrd库打开xls文件        return xlrd.open_workbook(file_path)    elif file_path.endswith('.xlsx'):        # 使用openpyxl库打开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    else:        return cell_valuedef main():    # 用户输入工作簿路径和后缀    file_path = input('请输入工作簿路径:')    file_suffix = input('请输入工作簿的后缀(xls或xlsx):')    # 打开工作簿    workbook = open_workbook(file_path)    while True:        # 获取并显示所有sheet名        sheet_names = get_sheet_names(workbook)        for i, name in enumerate(sheet_names):            print(f'{i+1}. {name}')                # 用户指定要操作的sheet        sheet_index = int(input('请选择要操作的sheet序号:')) - 1        sheet = workbook[sheet_names]        # 获取并显示所有列名        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        # 其他列的单元格格式选项        cell_formats =         # 用户指定转换后的单元格格式的编号        print('请选择转换后的单元格格式:')        for i, format in enumerate(cell_formats):            print(f'{i+1}. {format}')        cell_format_index = int(input('请输入选项序号:')) - 1        cell_format_name = cell_formats[cell_format_index]        cell_format_code = NumberFormat(formatCode=cell_format_name)        # 在该sheet中增加"转换后列"        sheet.insert_cols(column_index + 2)  # Excel是从1开始计数的,所以+2        # 遍历该列的每个单元格,进行格式转换        for i, cell in enumerate(sheet):  # Excel是从1开始计数的,所以+1            if i == 0:  # 跳过第一行(列名)                continue            original_value = cell.value            converted_value = convert_cell_format(original_value, cell_format_name)            cell.value = converted_value            cell.number_format = cell_format_code        # 保存工作簿        workbook.save(file_path)        # 继续转换询问        choice = input('是否继续转换?(是/否)')        if choice.lower() != '是':            breakif __name__ == '__main__':    main()在此代码中,使用了`openpyxl.styles.NumberFormat`来创建一个带有指定格式代码的格式对象。然后,在循环遍历单元格时,将此格式对象应用于单元格的`number_format`属性。这将确保单元格的值保持不变,并更改其显示格式。请根据需要进行适当调整,并选择正确的格式代码。

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

使用道具 举报

 楼主| 发表于 2024-3-20 10:50:43 | 显示全部楼层
FishC 发表于 2024-3-20 10:46
当然可以,请看下面的代码:import openpyxlfrom openpyxl import stylesfrom openpyxl.styles import  ...

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

使用道具 举报

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


非常抱歉,下面是符合Python格式的代码:

  1. import openpyxl
  2. from openpyxl.styles import NumberFormat

  3. def open_workbook(file_path):
  4.     if file_path.endswith('.xls'):
  5.         # 使用xlrd库打开xls文件
  6.         return xlrd.open_workbook(file_path)
  7.     elif file_path.endswith('.xlsx'):
  8.         # 使用openpyxl库打开xlsx文件
  9.         return openpyxl.load_workbook(file_path)
  10.     else:
  11.         raise ValueError('Invalid file format')

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

  19. def get_column_names(sheet):
  20.     if isinstance(sheet, xlrd.Sheet):
  21.         return sheet.row_values(0)  # 默认第一行为列名
  22.     elif isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet):
  23.         return [col.value for col in sheet.iter_cols(min_row=1, max_row=1)]
  24.     else:
  25.         raise ValueError('Invalid sheet type')

  26. def convert_cell_format(cell_value, cell_format):
  27.     # 根据用户指定的格式进行转换,这里只演示了两种常见的格式
  28.     if cell_format == '文本':
  29.         if isinstance(cell_value, (int, float)):
  30.             return str(cell_value)
  31.         else:
  32.             return cell_value
  33.     elif cell_format == '日期':
  34.         if isinstance(cell_value, str):
  35.             return datetime.datetime.strptime(cell_value, '%Y-%m-%d').date()
  36.         else:
  37.             return cell_value
  38.     else:
  39.         return cell_value

  40. def main():
  41.     # 用户输入工作簿路径和后缀
  42.     file_path = input('请输入工作簿路径:')
  43.     file_suffix = input('请输入工作簿的后缀(xls或xlsx):')

  44.     # 打开工作簿
  45.     workbook = open_workbook(file_path)

  46.     while True:
  47.         # 获取并显示所有sheet名
  48.         sheet_names = get_sheet_names(workbook)
  49.         for i, name in enumerate(sheet_names):
  50.             print(f'{i+1}. {name}')

  51.         # 用户指定要操作的sheet
  52.         sheet_index = int(input('请选择要操作的sheet序号:')) - 1
  53.         sheet = workbook[sheet_names[sheet_index]]

  54.         # 获取并显示所有列名
  55.         column_names = get_column_names(sheet)
  56.         for i, name in enumerate(column_names):
  57.             print(f'{i+1}. {name}')

  58.         # 用户指定要转换格式的列
  59.         column_index = int(input('请选择要转换格式的列序号:')) - 1
  60.         column_name = column_names[column_index]

  61.         # 其他列的单元格格式选项
  62.         cell_formats = ['文本', '日期']

  63.         # 用户指定转换后的单元格格式的编号
  64.         print('请选择转换后的单元格格式:')
  65.         for i, format in enumerate(cell_formats):
  66.             print(f'{i+1}. {format}')
  67.         cell_format_index = int(input('请输入选项序号:')) - 1
  68.         cell_format_name = cell_formats[cell_format_index]
  69.         cell_format_code = NumberFormat(formatCode=cell_format_name)

  70.         # 在该sheet中增加"转换后列"
  71.         sheet.insert_cols(column_index + 2)  # Excel是从1开始计数的,所以+2

  72.         # 遍历该列的每个单元格,进行格式转换
  73.         for i, cell in enumerate(sheet[column_name]):
  74.             if i == 0:  # 跳过第一行(列名)
  75.                 continue
  76.             original_value = cell.value
  77.             converted_value = convert_cell_format(original_value, cell_format_name)
  78.             cell.value = converted_value
  79.             cell.number_format = cell_format_code

  80.         # 保存工作簿
  81.         workbook.save(file_path)

  82.         # 继续转换询问
  83.         choice = input('是否继续转换?(是/否)')
  84.         if choice.lower() != '是':
  85.             break

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


非常抱歉给您带来了困扰,这是符合Python语法的代码。请注意使用缩进表示代码块的层次结构,并确保代码中的所有引号、括号和冒号都是配对的。如果还有其他问题,请随时提问。

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

使用道具 举报

 楼主| 发表于 2024-3-20 11:10:51 | 显示全部楼层
FishC 发表于 2024-3-20 10:51
非常抱歉,下面是符合Python格式的代码:

麻烦把文本型转换为数值型功能也加上
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 11:11:16 | 显示全部楼层
凊风 发表于 2024-03-20 11:10
麻烦把文本型转换为数值型功能也加上


好的,下面是添加将文本型转换为数值型的功能后的代码:import openpyxlfrom openpyxl.styles import NumberFormatdef open_workbook(file_path):    if file_path.endswith('.xls'):        # 使用xlrd库打开xls文件        return xlrd.open_workbook(file_path)    elif file_path.endswith('.xlsx'):        # 使用openpyxl库打开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     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 == '数值':        try:             return float(cell_value)        except ValueError:             return cell_value    else:        return cell_valuedef main():    # 用户输入工作簿路径和后缀    file_path = input('请输入工作簿路径:')    file_suffix = input('请输入工作簿的后缀(xls或xlsx):')    # 打开工作簿    workbook = open_workbook(file_path)    while True:        # 获取并显示所有sheet名        sheet_names = get_sheet_names(workbook)        for i, name in enumerate(sheet_names):            print(f'{i+1}. {name}')        # 用户指定要操作的sheet        sheet_index = int(input('请选择要操作的sheet序号:')) - 1        sheet = workbook[sheet_names]        # 获取并显示所有列名        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        # 其他列的单元格格式选项        cell_formats =         # 用户指定转换后的单元格格式的编号        print('请选择转换后的单元格格式:')        for i, format in enumerate(cell_formats):            print(f'{i+1}. {format}')        cell_format_index = int(input('请输入选项序号:')) - 1        cell_format_name = cell_formats        cell_format_code = NumberFormat(formatCode=cell_format_name)        # 在该sheet中增加"转换后列"        sheet.insert_cols(column_index + 2)  # Excel是从1开始计数的,所以+2        # 遍历该列的每个单元格,进行格式转换        for i, cell in enumerate(sheet):            if i == 0:  # 跳过第一行(列名)                continue            original_value = cell.value            converted_value = convert_cell_format(original_value, cell_format_name)            cell.value = converted_value            cell.number_format = cell_format_code        # 保存工作簿        workbook.save(file_path)        # 继续转换询问        choice = input('是否继续转换?(是/否)')        if choice.lower() != '是':            breakif __name__ == '__main__':    main()这个更新的代码中,我们添加了一个新的选项,允许将文本型数据转换为数值型数据。为此,我们使用了`float()`函数尝试将单元格的值转换为浮点数。如果转换失败,则保留原始的单元格值。 请注意,在代码中,我将“数值”作为转换后的单元格格式的选项之一,您可以根据需要自定义更多选项,并在`convert_cell_format()`函数中添加相应的处理逻辑。 请确保在运行代码之前使用`pip install openpyxl`命令安装`openpyxl`库。 让我知道是否还有任何问题!

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

使用道具 举报

 楼主| 发表于 2024-3-20 11:11:29 | 显示全部楼层
凊风 发表于 2024-3-20 11:10
麻烦把文本型转换为数值型功能也加上

还有文本型转常规型功能也加上
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 11:11:38 | 显示全部楼层
凊风 发表于 2024-03-20 11:11
还有文本型转常规型功能也加上


好的,下面是添加将文本型转换为常规型的功能后的代码:import openpyxlfrom openpyxl.styles import NumberFormat, NamedStyledef open_workbook(file_path):    if file_path.

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

使用道具 举报

 楼主| 发表于 2024-3-20 11:12:23 | 显示全部楼层
FishC 发表于 2024-3-20 11:11
好的,下面是添加将文本型转换为常规型的功能后的代码:import openpyxlfrom openpyxl.styles import N ...

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

使用道具 举报

发表于 2024-3-20 11:12:43 | 显示全部楼层
凊风 发表于 2024-03-20 11:12
你卡了吗?  回复请注意python格式


非常抱歉,我的回答被截断了。以下是完整的代码,包括将文本型转换为常规型的功能:

  1. import openpyxl
  2. from openpyxl.styles import NumberFormat, NamedStyle

  3. def open_workbook(file_path):
  4.     if file_path.endswith('.xls'):
  5.         return xlrd.open_workbook(file_path)
  6.     elif 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, xlrd.Book):
  12.         return workbook.sheet_names()
  13.     elif isinstance(workbook, openpyxl.Workbook):
  14.         return workbook.sheetnames
  15.     else:
  16.         raise ValueError('Invalid workbook type')

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

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

  39. def main():
  40.     file_path = input('请输入工作簿路径:')
  41.     file_suffix = input('请输入工作簿的后缀(xls或xlsx):')
  42.     workbook = open_workbook(file_path)
  43.    
  44.     while True:
  45.         sheet_names = get_sheet_names(workbook)
  46.         for i, name in enumerate(sheet_names):
  47.             print(f'{i+1}. {name}')
  48.         
  49.         sheet_index = int(input('请选择要操作的sheet序号:')) - 1
  50.         sheet = workbook[sheet_names[sheet_index]]
  51.         
  52.         column_names = get_column_names(sheet)
  53.         for i, name in enumerate(column_names):
  54.             print(f'{i+1}. {name}')
  55.         
  56.         column_index = int(input('请选择要转换格式的列序号:')) - 1
  57.         column_name = column_names[column_index]
  58.         
  59.         cell_formats = ['文本', '日期', '常规']
  60.         print('请选择转换后的单元格格式:')
  61.         for i, format in enumerate(cell_formats):
  62.             print(f'{i+1}. {format}')
  63.         cell_format_index = int(input('请输入选项序号:')) - 1
  64.         cell_format = cell_formats[cell_format_index]
  65.         
  66.         sheet.insert_cols(column_index + 2)
  67.         for i, cell in enumerate(sheet[column_index + 2]):
  68.             if i == 0:
  69.                 cell.style = None  # 清除单元格的样式
  70.             cell.value = convert_cell_format(cell.value, cell_format)
  71.             if cell_format == '常规':
  72.                 cell.number_format = NumberFormat('General')  # 设置单元格为常规型
  73.         
  74.         workbook.save(file_path)
  75.         
  76.         choice = input('是否继续转换?(是/否)')
  77.         if choice.lower() != '是':
  78.             break

  79. if __name__ == '__main__':
  80.     main()
复制代码


希望这次能够顺利地显示完整的代码。

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

使用道具 举报

 楼主| 发表于 2024-3-20 11:13:16 | 显示全部楼层
FishC 发表于 2024-3-20 11:12
非常抱歉,我的回答被截断了。以下是完整的代码,包括将文本型转换为常规型的功能:

还有转换为数值型功能也加上
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 11:13:40 | 显示全部楼层
凊风 发表于 2024-03-20 11:13
还有转换为数值型功能也加上


非常抱歉,以下是已经添加了转换为数值型的功能的完整代码:import openpyxlfrom openpyxl.styles import NumberFormat, NamedStyleimport xlrd, datetimedef 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 == '常规':        return cell_value    elif cell_format == '数值':        if isinstance(cell_value, str):            try:                return float(cell_value)            except ValueError:                return cell_value        else:            return cell_value    else:        return cell_valuedef 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_names]        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        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 i, cell in enumerate(sheet):            if i == 0:                cell.style = None  # 清除单元格的样式            cell.value = convert_cell_format(cell.value, cell_format)            if cell_format == '常规':                cell.number_format = NumberFormat('General')            elif cell_format == '数值':                cell.number_format = NumberFormat('0.00')  # 设置单元格为数值型,保留两位小数            workbook.save(file_path)        choice = input('是否继续转换?(是/否)')        if choice.lower() != '是':            breakif __name__ == '__main__':    main()希望这次代码能够顺利地显示完整,并且已经包含了将选定列转换为数值型的功能。如果您有任何问题,请随时提问。

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

使用道具 举报

 楼主| 发表于 2024-3-20 11:14:38 | 显示全部楼层
FishC 发表于 2024-3-20 11:13
非常抱歉,以下是已经添加了转换为数值型的功能的完整代码:import openpyxlfrom openpyxl.styles impo ...

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

使用道具 举报

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


非常抱歉,以下是已经添加了转换为数值型的功能的完整代码:

  1. import openpyxl
  2. from openpyxl.styles import NumberFormat, NamedStyle
  3. import xlrd
  4. import datetime

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

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

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

  26. def convert_cell_format(cell_value, cell_format):
  27.     if cell_format == '文本':
  28.         if isinstance(cell_value, (int, float)):
  29.             return str(cell_value)
  30.         else:
  31.             return cell_value
  32.     elif cell_format == '日期':
  33.         if isinstance(cell_value, str):
  34.             return datetime.datetime.strptime(cell_value, '%Y-%m-%d').date()
  35.         else:
  36.             return cell_value
  37.     elif cell_format == '常规':
  38.         return cell_value
  39.     elif cell_format == '数值':
  40.         if isinstance(cell_value, str):
  41.             try:
  42.                 return float(cell_value)
  43.             except ValueError:
  44.                 return cell_value
  45.         else:
  46.             return cell_value
  47.     else:
  48.         return cell_value

  49. def main():
  50.     file_path = input('请输入工作簿路径:')
  51.     file_suffix = input('请输入工作簿的后缀(xls或xlsx):')
  52.     workbook = open_workbook(file_path)
  53.     while True:
  54.         sheet_names = get_sheet_names(workbook)
  55.         for i, name in enumerate(sheet_names):
  56.             print(f'{i+1}. {name}')
  57.         sheet_index = int(input('请选择要操作的sheet序号:')) - 1
  58.         sheet = workbook[sheet_names]
  59.         column_names = get_column_names(sheet)
  60.         for i, name in enumerate(column_names):
  61.             print(f'{i+1}. {name}')
  62.         column_index = int(input('请选择要转换格式的列序号:')) - 1
  63.         column_name = column_names
  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
  70.         sheet.insert_cols(column_index + 2)
  71.         for i, cell in enumerate(sheet):
  72.             if i == 0:
  73.                 cell.style = None  # 清除单元格的样式
  74.             cell.value = convert_cell_format(cell.value, cell_format)
  75.             if cell_format == '常规':
  76.                 cell.number_format = NumberFormat('General')
  77.             elif cell_format == '数值':
  78.                 cell.number_format = NumberFormat('0.00')  # 设置单元格为数值型,保留两位小数
  79.         workbook.save(file_path)
  80.         choice = input('是否继续转换?(是/否)')
  81.         if choice.lower() != '是':
  82.             break

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


希望这次的代码格式能够符合您的需求。如果还有任何问题,请随时提问。

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

使用道具 举报

 楼主| 发表于 2024-3-20 11:16:05 | 显示全部楼层
FishC 发表于 2024-3-20 11:15
非常抱歉,以下是已经添加了转换为数值型的功能的完整代码:

要转换单元格成为什么格式,要让用户选择。。。。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-3-20 11:16:29 | 显示全部楼层
凊风 发表于 2024-03-20 11:16
要转换单元格成为什么格式,要让用户选择。。。。


非常抱歉,我理解错了您的需求。下面是已经更新了让用户选择转换后的单元格格式的代码:import openpyxlfrom openpyxl.styles import NumberFormat, NamedStyleimport xlrdimport datetimedef 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     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 == '常规':        return cell_value    elif cell_format == '数值':        if isinstance(cell_value, str):            try:                return float(cell_value)            except ValueError:                return cell_value        else:            return cell_value    else:        return cell_valuedef 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        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        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 i, cell in enumerate(sheet):            if i == 0:                cell.style = None  # 清除单元格的样式            cell.value = convert_cell_format(cell.value, cell_format)            if cell_format == '文本':                cell.number_format = NumberFormat('@')  # 设置单元格为文本格式            elif cell_format == '日期':                cell.number_format = NumberFormat('yyyy-mm-dd')  # 设置单元格为日期格式            elif cell_format == '常规':                cell.number_format = NumberFormat('General')            elif cell_format == '数值':                cell.number_format = NumberFormat('0.00')  # 设置单元格为数值型,保留两位小数        workbook.save(file_path)        choice = input('是否继续转换?(是/否)')        if choice.lower() != '是':            breakif __name__ == '__main__':    main()希望这次的代码能够满足您的需求。如果还有其他问题,请随时提问。

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

使用道具 举报

 楼主| 发表于 2024-3-20 11:17:46 | 显示全部楼层
FishC 发表于 2024-3-20 11:16
非常抱歉,我理解错了您的需求。下面是已经更新了让用户选择转换后的单元格格式的代码:import openpyx ...

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-28 18:39

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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