import pandas as pd
from openpyxl import load_workbook
def qyhhsj(source_file,source_sheetname,source_col,source_start_row,source_end_row,source_start_col,source_end_col,target_file,target_sheetname,target_start_row,target_end_row,target_start_col,target_end_col): """ source_file The path source_sheetname where the data source table is located The name of the sheet where the data source table
is
located
source_col
data The range of data columns required in the source table, such as from column C to column S, is written as C:S
source_start_row data source table start row
source_end_row data source table end
row source_start_col data source table start
column source_end_col data source table end column
target_file target table The path
target_sheetname The name of the sheet where the target table is located
target_start_row The start row of the target table target_end_row
The end row of the target table
target_start_col The start column of the target table
target_end_col The end column of the target table
"""
# 读取Excel文件
file_path = source_file
df = pd.read_excel(file_path, sheet_name=source_sheetname, header=None, index_col=None, usecols=source_col)
# Open the Excel file that needs to be replaced
wb2 = load_workbook(target_file)
# Get the sheet specified in the second Excel file
ws2 = wb2[target_sheetname]
# Select the area data to be exchanged required_data
= df.iloc[source_start_row:source_end_row, source_start_col: source_end_col]
print(required_data)
#Transpose the data in the selected area
required_data_T=required_data.T
print(required_data_T)
#Print and display the data of the first row and first column in required_data
# print(required_data.iloc[0, 0])
"""
# Specify to write Excel range
target_start_row = 5 # range starts at row 5
target_start_col = 2 # range starts at column 2
target_end_row = 17 # range ends at row 17
target_end_col = 19 # range ends at column 19
"""
ks_row=target_start_row
ks_col =target_start_col
# Traverse the rows and columns of the area to be replaced, and replace the value of each cell with the value of the corresponding row in the replacement data column
for i in range(target_start_row, target_end_row):
for j in range(target_start_col, target_end_col):
print (i, j)
# write data to row i and column j
ws2.cell(row=i, column=j, value=required_data_T.iloc[i - ks_row,j - ks_col])
# Save the modified first Excel file
wb2.save(target_file)
#Call the qyhhsj method, input the data from the 1st row to the 13th row of column C of the source table to the 2nd column, the 5th row to the 17th row of the target table's 'horizontal displacement' sheet qyhhsj(r'C:\
Users \Thinkpad\Desktop\Data final processing results (manual monitoring)\X displacement merge.xls','Sheet1','C:S',1,13,0,17,r'C:\Users\Thinkpad\Desktop \Data final processing results (manual monitoring)\Jinxi Reservoir data compilation 2023110--V6.xlsx','horizontal displacement',60,77,60,72)