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 ?數(shù)據(jù)源表格所在的路徑
? ? source_sheetname ? 數(shù)據(jù)源表格所在的sheet名稱
? ? source_col ? ? 數(shù)據(jù)源表格中需要的數(shù)據(jù)列的范圍,如從C列到S列,則寫成C:S
? ? source_start_row ?數(shù)據(jù)源表格開始行
? ? source_end_row ? 數(shù)據(jù)源表格結(jié)束行
? ? source_start_col 數(shù)據(jù)源表格開始列
? ? source_end_col ?數(shù)據(jù)源表格結(jié)束列
? ? target_file ? ? ? ? ?目標(biāo)表格所在的路徑
? ? target_sheetname ? ?目標(biāo)表格所在的sheet名稱
? ? target_start_row ? ? 目標(biāo)表格開始行
? ? target_end_row ? ?目標(biāo)表格結(jié)束行
? ? target_start_col ? ?目標(biāo)表格開始列
? ? target_end_col ? ?目標(biāo)表格結(jié)束列
? ? """
? ? # 讀取Excel文件
? ? file_path = source_file
? ? df = pd.read_excel(file_path, sheet_name=source_sheetname, header=None, index_col=None, usecols=source_col)
? ? # 打開需要替換數(shù)據(jù)的Excel文件
? ? wb2 = load_workbook(target_file)
? ? # 獲取第二個(gè)Excel文件中指定的sheet
? ? ws2 = wb2[target_sheetname]
? ? # 選擇要交換的區(qū)域數(shù)據(jù)
? ? required_data = df.iloc[source_start_row:source_end_row, source_start_col:source_end_col]
? ? print(required_data)
? ? #對(duì)選中區(qū)域數(shù)據(jù)進(jìn)行轉(zhuǎn)置
? ? required_data_T=required_data.T
? ? print(required_data_T)
? ? # 打印顯示required_data中第一行第一列的數(shù)據(jù)
? ? # print(required_data.iloc[0, 0])
? ? """
? ? # 指定要寫入的Excel區(qū)域
? ? target_start_row = 5 ?# 區(qū)域從第5行開始
? ? target_start_col = 2 ?# 區(qū)域從第2列開始
? ? target_end_row = 17 ?# 區(qū)域從第17行結(jié)束
? ? target_end_col = 19 ?# 區(qū)域從第19列結(jié)束
? ? """
? ? ks_row=target_start_row
? ? ks_col=target_start_col
? ? # 遍歷需要替換的區(qū)域行和列,將每個(gè)單元格的值替換成替換數(shù)據(jù)列中對(duì)應(yīng)行的值
? ? for i in range(target_start_row, target_end_row):
? ? ? ? for j in range(target_start_col, target_end_col):
? ? ? ? ? ? print(i, j)
? ? ? ? ? ? # 將數(shù)據(jù)寫入第i行第j列
? ? ? ? ? ? ws2.cell(row=i, column=j, value=required_data_T.iloc[i - ks_row,j - ks_col])
? ? # 保存修改后的第一個(gè)Excel文件
? ? wb2.save(target_file)文章來源:http://www.zghlxwxcb.cn/news/detail-578141.html
#調(diào)用qyhhsj方法,從源表格的第C列第1行到第13行數(shù)據(jù)輸入到目標(biāo)表格的'水平位移'sheet中第2列第5行到第17行中
qyhhsj( r'C:\Users\Thinkpad\Desktop\數(shù)據(jù)最終處理結(jié)果(人工監(jiān)測(cè))\X位移量合并.xls','Sheet1','C:S',1,13,0,17,r'C:\Users\Thinkpad\Desktop\數(shù)據(jù)最終處理結(jié)果(人工監(jiān)測(cè))\金溪水庫資料整編2023110--V6.xlsx','水平位移',60,77,60,72)
?文章來源地址http://www.zghlxwxcb.cn/news/detail-578141.html
到了這里,關(guān)于python 實(shí)現(xiàn)excel表選中區(qū)域數(shù)據(jù)轉(zhuǎn)置并存入另一個(gè)excel指定的區(qū)域中方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!