我做了很多环顾四周,找不到足够接近我正在寻找的东西。
我正在使用PowerShell来遍历数千个大致类似但在这里和那里之间存在细微差别的电子表格。此外,由于键和方向(不是我的工作,不能改变它),它不会在工作表的顶部使用传统的标题。因此,在工作表中的任何位置都有浮动的列组。有合并的标题列以及这些标题下的子列。 Picture for reference.这些部分也可以包含更多列。我只是在子列中提取信息,而不是合并的信息。
我能够获得我想要的数据范围,但是我很难将数据输出到新的工作簿。由于纸张的设置方式,我也拉的这些范围很奇怪。 (前$worksheet.Range("J14", "L40")
所以我有一个foreach
循环遍历每个文件并抓取我需要的数据并将其存储在这样的变量中:
$dataRange = $workSheet.Range($startCell, $endCell)
我的问题是,如何将这个特定ComObject中的所有行追加到另一个工作簿中?我一直在尝试循环遍历每个单元格的Text属性,但它会在新工作簿的第一列中继续打印它。
完整脚本:
."C:\Users\q1424360\Desktop\FunctionLibrary.ps1"
#$ErrorActionPreference= 'silentlycontinue'
#File Locations
$tempLocation = "C:\Users\q1424360\Desktop\Final\US"
$targetlocation = "C:\Users\q1424360\Desktop\Final\Test.xlsx"
$excel = New-Object -ComObject Excel.Application
$excel.visible = $false
$excel.DisplayAlerts = $false
#Get all files in directory recursively
Write "Loading Files..."
$files = Get-ChildItem -Path $tempLocation -Recurse | Where {
!$_.PSisContainer } | Sort name
foreach ($file in $files) {
$workBook = $excel.Workbooks.Open($file.FullName)
Write-Host -NoNewline "Working on " $file.Name
Write-Host
#Starts at 2 b/c of cache
for ($i = 2; $i -lt $workBook.Worksheets.Count + 1; $i++) {
$workSheet = $workBook.Worksheets.Item($i)
##Get User Account Type & Access Right Information column, find merge
column length, get all sub-columns
$localAdminCol = $workSheet.UsedRange.Find("User Account Type & Access
Right Information")
$accessMergeLength = $localAdminCol.MergeArea.Columns.Count;
#Logic for finding start cell of range
$accessStartCol = Convert-NumberToA1($localAdminCol.Column)
$accessStartRow = $localAdminCol.Row + 2
$startCell = "$($accessStartCol)$($accessStartRow)"
#Logic for finding end cell of range
$endCol = $localAdminCol.Column + $accessMergeLength - 1
$accessEndCol = Convert-NumberToA1($endCol)
#Hardcoded for 100 rows down
$usedRowCount =
$excel.WorksheetFunction.CountA($workSheet.Range($accessStartCol +
$accessStartRow + ":" + $accessStartCol + "100")) - 1
$accessEndRow = $accessStartRow + $usedRowCount
$endCell = "$($accessEndCol)$($accessEndRow)"
#The actual range that will be pulled for this area
$dataRange = $workSheet.Range($startCell, $endCell)
#$dataRange | Out-File $targetlocation -Append -Encoding ASCII
Release-Ref($workSheet)
Release-Ref($workBook)
}
$workBook.Close()
$excel.Quit()
}
Write "Files Loaded."
#Release all Com objects stored
Release-Ref($excel)