为什么使用 openpyxl 没有根据匹配列将数据写入现有 Excel 文件?

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

我有以下代码:

import warnings

warnings.filterwarnings("ignore", category=UserWarning, module="openpyxl")

file = f"{data_folder}\DIS_Ultimo_RWS_Decompositie4.xlsx"
book = load_workbook(file, data_only=False)
writer = pd.ExcelWriter(file, engine='openpyxl')
writer.workbook = book

bouwdelen = book["Bouwdelen"]
data = bouwdelen.values

# Skip one row (second row in Excel sheet is the actual header)
next(data)

# Get the existing columns in the sheet and their corresponding indices
columns = [c for c in next(data)[0:] if c is not None]
# Set the column names as keys and indices as values
columns_dict = {c: i+1 for i, c in enumerate(columns)}

# Change order of the dataframe columns according to column order of the Excel file
def reorder_columns(df, column_order):
    try:
        # Get the list of columns that exist in both the DataFrame and the column_order list
        existing_columns = list(filter(lambda col: col in df.columns, column_order))

        # Reindex the DataFrame using the desired column order
        df = df.reindex(columns=existing_columns)

        return df
    except Exception as e:
        print(f"An error occurred: {e}")
        return None

data_verwijderen = reorder_columns(data_verwijderen, columns)    

# Insert the rows of the dataframe to the target columns in the Excel file

for column_source, col_idx in columns_dict.items():
    if column_source in data_verwijderen.columns:
        for row_idx, row_data in enumerate(data_verwijderen[column_source].values, start=3):
            bouwdelen.cell(row=row_idx, column=col_idx, value=row_data)
                    
book.save(file)

由于某种原因,我的数据框中的数据未写入我现有的 Excel 文件。

如果我用以下代码替换某些代码行,它就可以工作:

for column_source, col_idx in columns.items():
    for column_df in data_verwijderen.columns[0:]:
        if column_source == column_df:
            for row_idx, row_data in enumerate(data_verwijderen[column_df].values, start=3):
                bouwdelen.cell(row=row_idx, column=col_idx, value=row_data)  
        else:
            continue  

但是,这似乎非常耗时。

有更好更高效的方法吗?

python openpyxl
© www.soinside.com 2019 - 2024. All rights reserved.