可樂陪雞翅
在處理大量Excel文件時,常常需要查找特定關鍵詞并批量獲取含該關鍵詞文件的路徑,以下方法可助你高效完成。
vba復制SubFindKeywordAndOutputPaths() DimfolderPathAsString DimfilePathAsString DimkeywordAsString DimwbAsWorkbook DimwsAsWorksheet DimfoundAsRange DimoutputFilePathAsString '設置文件夾路徑 folderPath="C:\YourFolderPath"'修改為實際文件夾路徑 '設置關鍵詞 keyword="YourKeyword"'修改為實際關鍵詞 '設置輸出文件路徑 outputFilePath="C:\Output.txt"'修改為實際輸出文件路徑 filePath=Dir(folderPath&"\*.xlsx") OpenoutputFilePathForOutputAs#1 DoWhilefilePath<>"" Setwb=Workbooks.Open(folderPath&"\"&filePath) ForEachwsInwb.Worksheets Setfound=ws.Cells.Find(What:=keyword,LookIn:=xlValues,LookAt:=xlPart) IfNotfoundIsNothingThen Print#1,folderPath&"\"&filePath ExitFor EndIf Nextws wb.CloseSaveChanges:=False filePath=Dir Loop Close#1 EndSub
pipinstallpandasopenpyxl
安裝所需庫。python復制importos importpandasaspd #設置文件夾路徑和關鍵詞 folder_path='C:/YourFolderPath' keyword='YourKeyword' output_file='C:/Output.txt' #遍歷文件夾中的所有文件 withopen(output_file,'w',encoding='utf-8')asf: forroot,dirs,filesinos.walk(folder_path): forfileinfiles: iffile.endswith('.xlsx')orfile.endswith('.xls'): file_path=os.path.join(root,file) try: excel_file=pd.ExcelFile(file_path) sheet_names=excel_file.sheet_names forsheet_nameinsheet_names: df=excel_file.parse(sheet_name) ifdf.astype(str).apply(lambdax:x.str.contains(keyword,na=False)).any().any(): f.write(file_path+'\n') break exceptExceptionase: print(f"Errorreading{file_path}:{e}")
.py
文件,在命令行中運行pythonyour_script_name.py
,腳本會在指定文件夾中查找包含關鍵詞的Excel文件,并將文件路徑輸出到指定的文本文件中。通過以上兩種方法,你可以高效地在多個Excel文件中查找特定關鍵詞,并批量輸出結果文件的路徑。
Copyright 2005-2023 yaolan.com 〖搖籃網〗 版權所有 備案號:滇ICP備2022004586號-57
聲明: 本站文章均來自互聯網,不代表本站觀點 如有異議 請與本站聯系 本站為非贏利性網站 不接受任何贊助和廣告 侵權刪除 478923@qq.com