Merge pull request #35 from francoislg/master

Allow reading a file already open in Excel
This commit is contained in:
Doug Finke
2015-08-21 12:25:39 -04:00
2 changed files with 20 additions and 9 deletions

View File

@@ -2,18 +2,20 @@ Add-Type -Path "$($PSScriptRoot)\EPPlus.dll"
function Import-Excel { function Import-Excel {
param( param(
[Parameter(ValueFromPipelineByPropertyName=$true)] [Alias("FullName")]
$FullName, [Parameter(ValueFromPipelineByPropertyName=$true, ValueFromPipeline=$true, Mandatory)]
$Path,
$Sheet=1, $Sheet=1,
[string[]]$Header [string[]]$Header
) )
Process { Process {
$FullName = (Resolve-Path $FullName).Path $Path = (Resolve-Path $Path).Path
write-debug "target excel file $FullName" write-debug "target excel file $Path"
$xl = New-Object OfficeOpenXml.ExcelPackage $FullName $stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path,"Open","Read","ReadWrite"
$xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $stream
$workbook = $xl.Workbook $workbook = $xl.Workbook
@@ -40,6 +42,8 @@ function Import-Excel {
[PSCustomObject]$h [PSCustomObject]$h
} }
$stream.Close()
$stream.Dispose()
$xl.Dispose() $xl.Dispose()
$xl = $null $xl = $null
} }
@@ -324,6 +328,7 @@ function ConvertFrom-ExcelSheet {
[CmdletBinding()] [CmdletBinding()]
param param
( (
[Alias("FullName")]
[Parameter(Mandatory = $true)] [Parameter(Mandatory = $true)]
[String] [String]
$Path, $Path,
@@ -340,7 +345,8 @@ function ConvertFrom-ExcelSheet {
) )
$Path = (Resolve-Path $Path).Path $Path = (Resolve-Path $Path).Path
$xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $Path $stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path,"Open","Read","ReadWrite"
$xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $stream
$workbook = $xl.Workbook $workbook = $xl.Workbook
$targetSheets = $workbook.Worksheets | Where {$_.Name -like $SheetName} $targetSheets = $workbook.Worksheets | Where {$_.Name -like $SheetName}
@@ -359,6 +365,8 @@ function ConvertFrom-ExcelSheet {
Import-Excel $Path -Sheet $($sheet.Name) | Export-Csv @params -Encoding $Encoding Import-Excel $Path -Sheet $($sheet.Name) | Export-Csv @params -Encoding $Encoding
} }
$stream.Close()
$stream.Dispose()
$xl.Dispose() $xl.Dispose()
} }

3
TestImportExcel.ps1 Normal file
View File

@@ -0,0 +1,3 @@
Import-Module "$PSScriptRoot/ImportExcel" -Force
Import-Excel "$PSScriptRoot/test.xlsx" -ErrorAction Stop