How to resolve TypeError ('expected ' + str(expected_type)) TypeError: expected <class 'float'> (Openpyxl 3.1.1)

问题描述 投票:0回答:1

在使用 openpyxl 从我的源工作簿中读取数据时,有没有办法可以解决此类型错误?我只是想提取值,而不是基础公式。我尝试使用以下方法将所有“-”实例转换为 0 以尝试解决此行的问题:

source_row_data = [0 if col_value == "-" else col_value for col_value in source_row_data]

这是正确的做法吗?这是错误:

文件“C:\Users\Kyle\AppData\Local\Programs\Python\Python311\Lib\site-packages\openpyxl\descriptors ase.py”,第 61 行,在 _convert 引发 TypeError('expected' + str(expected_type)) 类型错误:预期

和另一个(我认为是同一个问题):

文件“C:\Users\Kyle\AppData\Local\Programs\Python\Python311\Lib\site-packages\openpyxl\descriptors ase.py”,第 59 行,在 _convert 值 = 预期类型(值) ^^^^^^^^^^^^^^^^^^^^^ ValueError:无法将字符串转换为浮点数:'-'

import openpyxl
import calendar


# Open the destination workbook
try:
    dest_wb = openpyxl.load_workbook('Liquid Portfolio Attribution Analysis - Blank.xlsx')
except ValueError as e:
    print(e)
    print("Error occurred in cell:", e.cell.coordinate)
    print("Cell value:", e.cell.value)    

# Define the destination sheet and the starting row
dest_sheet = dest_wb['Data']

def get_maximum_rows(*, sheet_object):
    rows = 0
    for max_row, row in enumerate(sheet_object, 1):
        if not all(col.value is None for col in row):
            rows += 1
    return rows

# Get the maximum row with data in the destination sheet
dest_last_row = get_maximum_rows(sheet_object=dest_sheet)

# Set the starting row for copying data in the destination sheet
if dest_last_row == 4:
    dest_row = 5
else:
    dest_row = dest_last_row + 1

# Loop through each set of workbooks
for month in ['04']:
    for alpha in ['I', 'II']:
        # Open the source workbook
        wb_name = f'Copy of 2022-{month} Alpha {alpha} - Workbook.xlsx'
        wb = openpyxl.load_workbook(wb_name, data_only=True)

        # Get the PCAP sheet
        sheet_name = f'2022-{month} PCAP (R)'
        sheet = wb[sheet_name]

        # Copy the data and paste it into the destination sheet

        # Add the date to column B
        last_day = calendar.monthrange(2022, int(month))[1]
        date_str = f'{int(month)}/{last_day}/2022'
        dest_sheet[f'B{dest_row+1}'].value = date_str

        #Create dictionary with key value pairs to map source columns to destination columns
        data_map = {'A': 'C', 'B': 'E', 'D': 'F', 'F': 'G', 'H': 'H', 'U': 'J', 'AI': 'I', 'AO': 'K'}

        #Determines the last row to copy based on the max number of rows between the source and dest sheets
        last_row = sheet.max_row - 1
        print(f"Source sheet last row: {sheet.max_row}")
        print(f"Destination row: {dest_row}")

        
        for row in range(6, last_row + 1):
            dest_row +=1
            #print(f"Destination row: {dest_row}")
            source_row_data = [col.value for col in sheet[f'A{row}:AO{row}'][0]] #Creates a list of values for each column in the current row of source sheet
            source_row_data = [0 if col_value == "-" else col_value for col_value in source_row_data]
            if any(col_value is not None for col_value in source_row_data):
                for source_col, dest_col in data_map.items(): #Iterates through items in data_map dictionary
                    if len(source_col) == 1:
                        source_col_val = source_row_data[ord(source_col) - 65]  
                    else:
                        # Treat the column as a special case and manually convert it to the corresponding column number
                        col_num = (ord(source_col[0]) - 64) * 26 + (ord(source_col[1]) - 65)
                        source_col_val = source_row_data[col_num - 1]

                    #Sets dest_col_val to the cell in the destination sheet corr. to current dest column being iterated over and current row
                    dest_col_val = dest_sheet[f'{dest_col}{dest_row}'] 
                    if source_col in ['H', 'U', 'AI'] and row == last_row:
                        dest_col_val.value = None
                    else:
                        dest_col_val.value = source_col_val
                #print(f"Source column length: {len(source_col)}")
            else:
                print(f'Row {row} has blank data')

        wb.close()

dest_wb.save('Liquid Portfolio Attribution Analysis - Copy 2.xlsx')
python-3.x openpyxl
1个回答
0
投票

你好 Kyle Massimilian,

这个错误是因为

col_value
在某些情况下是一个值为“-”的字符串,而
openpyxl
需要一个浮点值。您可以将“-”替换为 0 以查看是否修复它,但只有在您确认包含“-”的单元格实际值为 0 时,它才会按预期工作。如果是这样,则您的方法没问题。

当您确认要将“-”替换为0时,您可以将导致错误的行修改为:

source_row_data = [float(col_value) if col_value != "-" else 0 for col_value in source_row_data]
© www.soinside.com 2019 - 2024. All rights reserved.