|
楼主 |
发表于 2023-5-24 09:19
|
显示全部楼层
下面的代码能完美执行想要的结果 ,但仅支持XLSX文件,XLS的不支持 大哥给看下怎么修改啊
<# :
echo on & setlocal EnableDelayedExpansion
for /f "delims=" %%i in ('"dir /a/s/b/on 元数据*.*"') do (
set file=%%~fi
set file=!file:/=/!
echo !file! >> files1.txt
)
powershell -noprofile -NoLogo "iex (${%~f0} | out-string)"
pause
#>
function get-data([int]$startrow, [int]$startcol, [int]$endrow, [int]$endcol, [string]$pat, [string[]]$files1, [string[]]$files2) {
foreach ($file2 in $files2) {
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$wb = $excel.Workbooks.Open($file2)
$ws = $wb.Sheets.Item(1)
$sr = $ws.Range($ws.Cells.Item($startrow, $startcol), $ws.Cells.Item($endrow, $endcol))
$sd = $sr.Value2
$found = $false
foreach ($file1 in $files1) {
$dwb = $excel.Workbooks.Open($file1)
$dws = $dwb.Sheets.Item(2)
$fc = $dws.UsedRange.Find($pat)
if ($fc -ne $null) {
$found = $true
$rown = $fc.Row
for ($i = 0; $i -le $endrow-$startrow; $i++) {
$dws.Rows.Item($rown + 1).EntireRow.Insert()
}
$dsr = $dws.Range($dws.Cells.Item($rown + 1, $startcol), $dws.Cells.Item($rown + 1 + ($endrow - $startrow), $endcol))
$dsr = $dsr.Resize($sr.Rows.Count, $sr.Columns.Count)
$dsr.Value2 = $sd
$sr.Copy()
$dsr.PasteSpecial(-4122)
for ($i = 1; $i -le $dsr.Rows.Count; $i++) {
# $val = $dsr.Cells.Item($i, 1).Offset(-1, 0)
# $dsr.Cells.Item($i, 1).Value2 = $val.Value2
}
for ($i = 1; $i -le $dsr.Rows.Count; $i++) {
$val = $dsr.Cells.Item($i, 4).Offset(-5, 0)
$dsr.Cells.Item($i, 4).Value2 = $val.Value2
}
$dwb.Close($true)
Start-Sleep -Milliseconds 500
break
}
$dwb.Close($true)
Start-Sleep -Milliseconds 500
}
if (!$found) {
Write-Host "Pattern $pat not found in any file."
} else {
$excel.DisplayAlerts = $false
$wb.Close($false)
$excel.Quit()
[Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
}
}
}
$files1 = Get-Content "files1.txt"
$files2 = Get-Content "files2.txt"
get-data -startrow 1 -startcol 2 -endrow 4 -endcol 9 -pat 12100 -files1 $files1 -files2 $files2
get-data -startrow 6 -startcol 2 -endrow 8 -endcol 9 -pat 1011 -files1 $files1 -files2 $files2
get-data -startrow 10 -startcol 2 -endrow 11 -endcol 9 -pat 1013 -files1 $files1 -files2 $files2 |
|