-
Notifications
You must be signed in to change notification settings - Fork 2
/
convert-worksheets-in-dir.ps1
52 lines (42 loc) · 1.38 KB
/
convert-worksheets-in-dir.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
add-type -path 'C:\Program Files (x86)\Microsoft Office\Office16\DCF\Microsoft.Office.Interop.Excel.dll'
function export-CSV {
param (
[string] $dir, # Must not end in a (back-)slash
[string] $sheetName
)
$dir = resolve-path $dir
$xls = new-object Microsoft.Office.Interop.Excel.ApplicationClass
$xls.visible = $true
$xls.displayAlerts = $false # don't display message box when exporting a worksheet as CSV.
foreach ($wbFile in get-childItem $dir\*.xls*) {
$wb = $xls.workbooks.open($wbFile.fullName)
try {
$sh = $wb.sheets($sheetName)
}
catch {
if ($_.exception.message -match 'Invalid index.') {
write-host "Expected sheet not found in $($wb.name)"
$wb.close()
continue
}
throw $_
}
$sh.select()
$csvFile = "$dir\$($wbFile.basename).csv"
$wb.saveAs($csvFile, 6, $false)
write-host "$csvFile was saved"
$wb.close()
}
$xls.quit()
}
export-CSV "~/ZZZ/Excel/Export-CSV" 'Approval_Logs'
#
# Make sure Excel process is stopped/terminated when
# sheets are exported
# The following two methods Collect() and WaitForPendingFinalizers()
# must be called in the scope that called the scope
# where interop is used
# https://stackoverflow.com/a/25135685/180275
#
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()