技能A : PowerShell + 技能B : 資料夾管理
技能A : Powershell
設定要讀取的資料夾和輸出的檔案名稱
$folderPath = “C:\Folder”
$outputFile = “C:\Folder\MergedFile.xlsx”
取得資料夾中的所有 Excel 檔案
$filesToMerge = Get-ChildItem $folderPath | Where-Object { $_.Extension -eq “.xls” }
要使用的 COM 物件
$excelApp = New-Object -ComObject Excel.Application
$excelApp.Visible = $false
$excelApp.DisplayAlerts = $false
建立一個新的工作簿
$newWorkbook = $excelApp.Workbooks.Add()
開始合併
foreach ($file in $filesToMerge) {
# 打開要合併的檔案
$workbook = $excelApp.Workbooks.Open($file.FullName)
# 複製資料到新的工作簿中
foreach ($worksheet in $workbook.Worksheets) {
$worksheetCopy = $worksheet.Copy($newWorkbook.Worksheets.Item($newWorkbook.Worksheets.Count))
}
# 關閉目前的工作簿
$workbook.Close()
}
儲存新的工作簿
$newWorkbook.SaveAs($outputFile)
關閉 Excel
$newWorkbook.Close()
$excelApp.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelApp) | Out-Null
技能B : 資料夾管理
const clearExcelFiles = async () => {
const files = await api.files();
const excelFiles = files.filter(file => file.endsWith(‘.xlsx’) || file.endsWith(‘.xls’) || file.endsWith(‘.csv’) || file.endsWith(‘.txt’));
for (const file of excelFiles) {
await api.remove(file);
}
};
clearExcelFiles();
後續T1同仁協助修正,只使用Powershell,看起來可以正常執行,還在觀察中
設定要讀取的資料夾和輸出的檔案名稱
$folderPath = “D:\RPA\T1技術交流\刪除資料夾Data\原檔”
$outputFile = “D:\RPA\T1技術交流\刪除資料夾Data\Output\MergedFile.xlsx”
取得資料夾中的所有 Excel 檔案
$filesToMerge = Get-ChildItem $folderPath | Where-Object { $_.Extension -eq “.xls” }
要使用的 COM 物件
$excelApp = New-Object -ComObject Excel.Application
$excelApp.Visible = $false
$excelApp.DisplayAlerts = $false
建立一個新的工作簿
$newWorkbook = $excelApp.Workbooks.Add()
開始合併
foreach ($file in $filesToMerge) {
# 打開要合併的檔案
$workbook = $excelApp.Workbooks.Open($file.FullName)
# 複製資料到新的工作簿中
foreach ($worksheet in $workbook.Worksheets) {
$worksheetCopy = $worksheet.Copy($newWorkbook.Worksheets.Item($newWorkbook.Worksheets.Count))
}
# 關閉目前的工作簿
$workbook.Close()
}
儲存新的工作簿
$newWorkbook.SaveAs($outputFile)
關閉 Excel
$newWorkbook.Close()
$excelApp.Quit()
刪除 Excel, CSV, 和 TXT 檔案
Get-ChildItem $folderPath -Include .xls,.txt,*.csv -Recurse | Remove-Item