我有两个 Excel 电子表格 X 和 Y。我需要打开电子表格 X,导航到所需的列,然后应用名称过滤器。一旦找到指定的名称,它应该移动到所需的列并仅过滤与该名称的行对应的单元格的值。之后,它应该复制该值并将其粘贴到电子表格 Y 中所需的单元格和列中。此过程与使用 XLOOKUP 类似,但更强大。
我能够创建此代码,并且它有效。但是,当它尝试在实际工作表中查找可能是公式的名称(例如 CONCATATED)时,它不会检索该值。代码运行但不执行任何操作。另一个问题是,名称过滤器仅在我将其应用于第一列时才有效。我希望能够选择我想要的任何列。整体代码运行良好;只需要这两个调整。我还要求 ChatGPT 对代码进行注释,这样你们会更容易理解它。
from pathlib import Path
from openpyxl import load_workbook
import re
# Load the source spreadsheet (X)
source_workbook = load_workbook(r'')
# Load the destination spreadsheet (Y)
destination_workbook = load_workbook(r'')
# Select the specific source sheet (X - Lead_Time_Categories)
source_sheet_sheet2 = source_workbook['']
# Select the specific source sheet (X - Lead_Time_Categories)
source_sheet_sheet3 = source_workbook['']
# Select the specific destination sheet (Y - RESULT)
destination_sheet = destination_workbook['']
# Value to be searched in column 1 of Sheet2
name_to_search_sheet2 = ''
# Indices of the desired columns in Sheet2 (e.g., columns 2, 4, and 6)
indices_columns_sheet2 = [19, 21, 23, 25, 27, 29]
# Coordinates of the destination cells in Sheet1 for Sheet2
coordinates_cells_sheet2 = ['L80', 'M80', 'N80', 'O80', 'P80', 'Q80']
# Value to be searched in column 1 of Sheet3
name_to_search_sheet3 = ''
# Indices of the desired columns in Sheet3 (e.g., columns 3, 5, and 7)
indices_columns_sheet3 = [19, 21, 23, 25, 27, 29]
# Coordinates of the destination cells in Sheet1 for Sheet3
coordinates_cells_sheet3 = ['L79', 'M79', 'N79', 'O79', 'P79', 'Q79']
# Function to extract values and fill destination cells
def extract_values_and_fill(source, name_to_search, indices_columns, coordinates_cells):
# Initialize variables to store found cell values
cell_values = []
# Iterate through cells in column 1 of the source sheet
for row in source.iter_rows(min_row=1, max_row=source.max_row, min_col=1, max_col=source.max_column):
if row[0].value == name_to_search:
# Copy information from desired columns
for col_index in indices_columns:
cell_values.append(row[col_index - 1].value)
# Return the found values
return cell_values
# Extract values and fill cells in Sheet2
values_sheet2 = extract_values_and_fill(source_sheet_sheet2, name_to_search_sheet2, indices_columns_sheet2, coordinates_cells_sheet2)
if values_sheet2:
# Fill corresponding cells in the destination sheet (Sheet1)
for i, value in enumerate(values_sheet2):
coordinate = coordinates_cells_sheet2[i]
destination_sheet[coordinate].value = value
# Extract values and fill cells in Sheet3
values_sheet3 = extract_values_and_fill(source_sheet_sheet3, name_to_search_sheet3, indices_columns_sheet3, coordinates_cells_sheet3)
if values_sheet3:
# Fill corresponding cells in the destination sheet (Sheet1)
for i, value in enumerate(values_sheet3):
coordinate = coordinates_cells_sheet3[i]
destination_sheet[coordinate].value = value
# Save the destination workbook
destination_workbook.save(r'')
一年前学了编程,但是因为国内的情况就停止了,想重新工作
在我的国家没有任何工作机会可以让我收取笔记本电脑的价格。请尽快帮助我。谢谢。我来自叙利亚。如果是这样,那会是什么?