FishC 发表于 2024-3-20 10:23:37

凊风 发表于 2024-03-20 10:23
为什么身份证号(18位文本型)转换后还是文本型呢?

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

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

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

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

凊风 发表于 2024-3-20 10:42:36

凊风 发表于 2024-3-20 10:23
为什么身份证号(18位文本型)转换后还是文本型呢?

请问能不能通过保留原单元格value然后设置此单元格格式的方法以来实现呢?

FishC 发表于 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 小助理,如未能正确解答您的问题,请继续追问。

凊风 发表于 2024-3-20 10:46:24

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

能否在本贴第九十六楼的基础上加入此功能呢?

FishC 发表于 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     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      # 获取并显示所有列名      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):# 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 小助理,如未能正确解答您的问题,请继续追问。

凊风 发表于 2024-3-20 10:50:43

FishC 发表于 2024-3-20 10:46
当然可以,请看下面的代码:import openpyxlfrom openpyxl import stylesfrom openpyxl.styles import...

回复请注意python格式

FishC 发表于 2024-3-20 10:51:13

凊风 发表于 2024-03-20 10:50
回复请注意python格式

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

import openpyxl
from openpyxl.styles import NumberFormat

def 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
    else:
      return cell_value

def 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]

      # 获取并显示所有列名
      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() != '是':
            break

if __name__ == '__main__':
    main()

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

凊风 发表于 2024-3-20 11:10:51

FishC 发表于 2024-3-20 10:51
非常抱歉,下面是符合Python格式的代码:




麻烦把文本型转换为数值型功能也加上

FishC 发表于 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      # 获取并显示所有列名      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 小助理,如未能正确解答您的问题,请继续追问。

凊风 发表于 2024-3-20 11:11:29

凊风 发表于 2024-3-20 11:10
麻烦把文本型转换为数值型功能也加上

还有文本型转常规型功能也加上

FishC 发表于 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 小助理,如未能正确解答您的问题,请继续追问。

凊风 发表于 2024-3-20 11:12:23

FishC 发表于 2024-3-20 11:11
好的,下面是添加将文本型转换为常规型的功能后的代码:import openpyxlfrom openpyxl.styles import N ...

你卡了吗?回复请注意python格式

FishC 发表于 2024-3-20 11:12:43

凊风 发表于 2024-03-20 11:12
你卡了吗?回复请注意python格式

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

import openpyxl
from openpyxl.styles import NumberFormat, NamedStyle

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)
    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
    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]
      
      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')# 设置单元格为常规型
      
      workbook.save(file_path)
      
      choice = input('是否继续转换?(是/否)')
      if choice.lower() != '是':
            break

if __name__ == '__main__':
    main()

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

凊风 发表于 2024-3-20 11:13:16

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




还有转换为数值型功能也加上

FishC 发表于 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     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('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 小助理,如未能正确解答您的问题,请继续追问。

凊风 发表于 2024-3-20 11:14:38

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

。。回复请注意python格式

FishC 发表于 2024-3-20 11:15:09

凊风 发表于 2024-03-20 11:14
。。回复请注意python格式

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

import openpyxl
from openpyxl.styles import NumberFormat, NamedStyle
import xlrd
import datetime

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)
    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_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
      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() != '是':
            break

if __name__ == '__main__':
    main()

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

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

凊风 发表于 2024-3-20 11:16:05

FishC 发表于 2024-3-20 11:15
非常抱歉,以下是已经添加了转换为数值型的功能的完整代码:




要转换单元格成为什么格式,要让用户选择。。。。

FishC 发表于 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 小助理,如未能正确解答您的问题,请继续追问。

凊风 发表于 2024-3-20 11:17:46

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

回复请注意python格式
页: 1 2 3 4 5 [6] 7
查看完整版本: 单元格格式转换求教2~~