Skip to content

Commit

Permalink
Merge pull request #590 from jhoneill/master
Browse files Browse the repository at this point in the history
Fixed case on file names, and applied a new rules from script analyzer
  • Loading branch information
dfinke authored May 1, 2019
2 parents 337af82 + 899a821 commit e7d2b52
Show file tree
Hide file tree
Showing 33 changed files with 226 additions and 188 deletions.
2 changes: 1 addition & 1 deletion AddConditionalFormatting.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@
$Address = "$($Address.Row):$($Address.Row)"
}
elseif ($Address -is [OfficeOpenXml.ExcelColumn]) {
$Address = [OfficeOpenXml.ExcelAddress]::new(1,$address.ColumnMin,1,$address.ColumnMax).Address -replace '1',''
$Address = (New-Object 'OfficeOpenXml.ExcelAddress' @(1, $address.ColumnMin, 1, $address.ColumnMax).Address) -replace '1',''
if ($Address -notmatch ':') {$Address = "$Address`:$Address"}
}
if ( $Address -is [string] -and $Address -match "!") {$Address = $Address -replace '^.*!',''}
Expand Down
4 changes: 2 additions & 2 deletions AddDataValidation.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@
}
else {
#We should accept, a worksheet and a name of a range or a cell address; a table; the address of a table; a named range; a row, a column or .Cells[ ]
if (-not $WorkSheet -and $Range.worksheet) {$WorkSheet = $Range.worksheet}
if (-not $WorkSheet -and $Range.worksheet) {$WorkSheet = $Range.worksheet}
if ($Range.Address) {$Range = $Range.Address}

if ($Range -isnot [string] -or -not $WorkSheet) {Write-Warning -Message "You need to provide a worksheet and range of cells." ;return}
#else we assume Range is a range.

Expand Down
2 changes: 1 addition & 1 deletion ConvertFromExcelData.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ function ConvertFrom-ExcelData {
.SYNOPSIS
Reads data from a sheet, and for each row, calls a custom scriptblock with a list of property names and the row of data.
.EXAMPLE
ConvertFrom-ExcelData .\testSQLGen.xlsx {
param($propertyNames, $record)
Expand Down
2 changes: 1 addition & 1 deletion DoTests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ $PSVersionTable.PSVersion

## Create the zip before the tests run
## Otherwise the EPPlus.dll is in use after the Pester run
$ModuleVersion = (Get-Content -Raw .\ImportExcel.psd1) | Invoke-Expression | ForEach-Object ModuleVersion
$ModuleVersion = (Invoke-Command -ScriptBlock ([scriptblock]::Create((Get-Content -Raw .\ImportExcel.psd1)))).moduleVersion

if (!$DontCreateZip) {
$dest = "ImportExcel-{0}-{1}.zip" -f $ModuleVersion, (Get-Date).ToString("yyyyMMddHHmmss")
Expand Down
104 changes: 57 additions & 47 deletions Export-Excel.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@
.PARAMETER RangeName
Makes the data in the worksheet a named range.
.PARAMETER TableName
Makes the data in the worksheet a table with a name, and applies a style to it. Name must not contain spaces.
Makes the data in the worksheet a table with a name, and applies a style to it. The name must not contain spaces. If a style is specified without a name, table1, table2 etc. will be used.
.PARAMETER TableStyle
Selects the style for the named table - defaults to 'Medium6'.
Selects the style for the named table - if a name is specified without a style, 'Medium6' is used as a default.
.PARAMETER BarChart
Creates a "quick" bar chart using the first text column as labels and the first numeric column as values
.PARAMETER ColumnChart
Expand Down Expand Up @@ -418,15 +418,15 @@
.LINK
https://github.com/dfinke/ImportExcel
#>
[CmdletBinding(DefaultParameterSetName = 'Default')]
[CmdletBinding(DefaultParameterSetName = 'Now')]
[OutputType([OfficeOpenXml.ExcelPackage])]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
Param(
[Parameter(ParameterSetName = "Default", Position = 0)]
[Parameter(ParameterSetName = "Table" , Position = 0)]

[Parameter(Mandatory = $true, ParameterSetName = "Path", Position = 0)]
[String]$Path,
[Parameter(Mandatory = $true, ParameterSetName = "PackageDefault")]
[Parameter(Mandatory = $true, ParameterSetName = "PackageTable")]
[Parameter(Mandatory = $true, ParameterSetName = "Package")]

[OfficeOpenXml.ExcelPackage]$ExcelPackage,
[Parameter(ValueFromPipeline = $true)]
[Alias('TargetData')]
Expand Down Expand Up @@ -462,8 +462,8 @@
[Switch]$FreezeFirstColumn,
[Switch]$FreezeTopRowFirstColumn,
[Int[]]$FreezePane,
[Parameter(ParameterSetName = 'Default')]
[Parameter(ParameterSetName = 'PackageDefault')]


[Switch]$AutoFilter,
[Switch]$BoldTopRow,
[Switch]$NoHeader,
Expand All @@ -478,11 +478,11 @@
elseif ($_[0] -notmatch '[a-z]') { throw 'Tablename starts with an invalid character.' }
else { $true }
})]
[Parameter(ParameterSetName = 'Table' , Mandatory = $true, ValueFromPipelineByPropertyName)]
[Parameter(ParameterSetName = 'PackageTable' , Mandatory = $true, ValueFromPipelineByPropertyName)]


[String]$TableName,
[Parameter(ParameterSetName = 'Table')]
[Parameter(ParameterSetName = 'PackageTable')]


[OfficeOpenXml.Table.TableStyles]$TableStyle,
[Switch]$Barchart,
[Switch]$PieChart,
Expand Down Expand Up @@ -793,24 +793,30 @@
Add-ExcelName -RangeName $targetRangeName -Range $ws.Cells[$targetRow, ($StartColumn + $c ), $LastRow, ($StartColumn + $c )]
try {#this test can throw with some names, surpress any error
if ([OfficeOpenXml.FormulaParsing.ExcelUtilities.ExcelAddressUtil]::IsValidAddress(($targetRangeName -replace '\W' , '_' ))) {
Write-Warning "AutoNameRange: Property name '$targetRangeName' is also a valid Excel address and may cause issues. Consider renaming the property name."
Write-Warning -Message "AutoNameRange: Property name '$targetRangeName' is also a valid Excel address and may cause issues. Consider renaming the property."
}
} Catch {}
}
Catch {
Write-Warning -Message "AutoNameRange: Testing '$targetRangeName' caused an error. This should be harmless, but a change of property name may be needed.."
}
}
}
catch {Write-Warning -Message "Failed adding named ranges to worksheet '$WorksheetName': $_" }
}
#Empty string is not allowed as a name for ranges or tables.
if ($RangeName) { Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $RangeName}

if ($TableName) {
#Allow table to be inserted by specifying Name, or Style or both; only process autoFilter if there is no table (they clash).
if ($TableName) {
if ($PSBoundParameters.ContainsKey('TableStyle')) {
Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName -TableStyle $TableStyle
}
else {Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName}
}

if ($AutoFilter) {
elseif ($PSBoundParameters.ContainsKey('TableStyle')) {
Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName "" -TableStyle $TableStyle
}
elseif ($AutoFilter) {
try {
$ws.Cells[$dataRange].AutoFilter = $true
Write-Verbose -Message "Enabled autofilter. "
Expand Down Expand Up @@ -1235,7 +1241,7 @@ function Select-Worksheet {
}
}

Function Add-ExcelName {
function Add-ExcelName {
<#
.SYNOPSIS
Adds a named-range to an existing Excel worksheet.
Expand Down Expand Up @@ -1299,9 +1305,8 @@ function Add-ExcelTable {
#The range of cells to assign to a table.
[Parameter(Mandatory=$true)]
[OfficeOpenXml.ExcelRange]$Range,
#The name for the Table - this should be unqiue in the Workbook.
[Parameter(Mandatory=$true)]
[String]$TableName,
#The name for the Table - this should be unqiue in the Workbook - auto generated names will be used if this is left empty.
[String]$TableName = "",
#The Style for the table, by default "Medium6" is used
[OfficeOpenXml.Table.TableStyles]$TableStyle = 'Medium6',
#By default the header row is shown - it can be turned off with -ShowHeader:$false.
Expand All @@ -1324,32 +1329,37 @@ function Add-ExcelTable {
[Switch]$PassThru
)
try {
if ([OfficeOpenXml.FormulaParsing.ExcelUtilities.ExcelAddressUtil]::IsValidAddress($TableName)) {
Write-Warning -Message "$tableName reads as an Excel address, and so is not allowed as a table name."
return
}
if ($tableName -notMatch '^[A-Z]') {
Write-Warning -Message "$tableName is not allowed as a table name because it does not begin with a letter."
return
}
if ($TableName -match "\W") {
Write-Warning -Message "At least one character in $TableName is illegal in a table name and will be replaced with '_' . "
$TableName = $TableName -replace '\W', '_'
}
$ws = $Range.Worksheet
#if the table exists in this worksheet, update it.
if ($ws.Tables[$TableName]) {
$tbl =$ws.Tables[$TableName]
$tbl.TableXml.table.ref = $Range.Address
Write-Verbose -Message "Re-defined table '$TableName', now at $($Range.Address)."
}
elseif ($ws.Workbook.Worksheets.Tables.Name -contains $TableName) {
Write-Warning -Message "The Table name '$TableName' is already used on a different worksheet."
return
if ($TableName -eq "" -or $null -eq $TableName) {
$tbl = $Range.Worksheet.Tables.Add($Range, "")
}
else {
$tbl = $ws.Tables.Add($Range, $TableName)
Write-Verbose -Message "Defined table '$TableName' at $($Range.Address)"
if ([OfficeOpenXml.FormulaParsing.ExcelUtilities.ExcelAddressUtil]::IsValidAddress($TableName)) {
Write-Warning -Message "$TableName reads as an Excel address, and so is not allowed as a table name."
return
}
if ($TableName -notMatch '^[A-Z]') {
Write-Warning -Message "$TableName is not allowed as a table name because it does not begin with a letter."
return
}
if ($TableName -match "\W") {
Write-Warning -Message "At least one character in $TableName is illegal in a table name and will be replaced with '_' . "
$TableName = $TableName -replace '\W', '_'
}
$ws = $Range.Worksheet
#if the table exists in this worksheet, update it.
if ($ws.Tables[$TableName]) {
$tbl =$ws.Tables[$TableName]
$tbl.TableXml.table.ref = $Range.Address
Write-Verbose -Message "Re-defined table '$TableName', now at $($Range.Address)."
}
elseif ($ws.Workbook.Worksheets.Tables.Name -contains $TableName) {
Write-Warning -Message "The Table name '$TableName' is already used on a different worksheet."
return
}
else {
$tbl = $ws.Tables.Add($Range, $TableName)
Write-Verbose -Message "Defined table '$($tbl.Name)' at $($Range.Address)"
}
}
#it seems that show total changes some of the others, so the sequence matters.
if ($PSBoundParameters.ContainsKey('ShowHeader')) {$tbl.ShowHeader = [bool]$ShowHeader}
Expand All @@ -1358,7 +1368,7 @@ function Add-ExcelTable {
foreach ($k in $TotalSettings.keys) {
if (-not $tbl.Columns[$k]) {Write-Warning -Message "Table does not have a Column '$k'."}
elseif ($TotalSettings[$k] -notin @("Average", "Count", "CountNums", "Max", "Min", "None", "StdDev", "Sum", "Var") ) {
Write-wanring "'$($TotalSettings[$k])' is not a valid total function."
Write-Warning -Message "'$($TotalSettings[$k])' is not a valid total function."
}
else {$tbl.Columns[$k].TotalsRowFunction = $TotalSettings[$k]}
}
Expand Down
48 changes: 24 additions & 24 deletions Export-charts.ps1
Original file line number Diff line number Diff line change
@@ -1,49 +1,49 @@
<#
.Synopsis
Exports the charts in an Excel spreadSheet
Exports the charts in an Excel spreadSheet
.Example
Export-Charts .\test.xlsx
Exports the charts in test.xlsx to JPEG files in the current directory.
.Example
Export-Charts -path .\test,xlsx -destination [System.Environment+SpecialFolder]::MyDocuments -outputType PNG -passthrough
Exports the charts to PNG files in MyDocuments , and returns file objects representing the newly created files
Export-Charts -path .\test,xlsx -destination [System.Environment+SpecialFolder]::MyDocuments -outputType PNG -passthrough
Exports the charts to PNG files in MyDocuments , and returns file objects representing the newly created files
#>
Param (
#Path to the Excel file whose chars we will export.
$Path = "C:\Users\public\Documents\stats.xlsx",
#If specified, output file objects representing the image files
[switch]$Passthru,
#Format to write - JPG by default
#Path to the Excel file whose chars we will export.
$Path = "C:\Users\public\Documents\stats.xlsx",
#If specified, output file objects representing the image files
[switch]$Passthru,
#Format to write - JPG by default
[ValidateSet("JPG","PNG","GIF")]
$OutputType = "JPG",
#Folder to write image files to (defaults to same one as the Excel file is in)
$OutputType = "JPG",
#Folder to write image files to (defaults to same one as the Excel file is in)
$Destination
)

#if no output folder was specified, set destination to the folder where the Excel file came from
if (-not $Destination) {$Destination = Split-Path -Path $Path -Parent }
#if no output folder was specified, set destination to the folder where the Excel file came from
if (-not $Destination) {$Destination = Split-Path -Path $Path -Parent }

#Call up Excel and tell it to open the file.
try { $excelApp = New-Object -ComObject "Excel.Application" }
catch { Write-Warning "Could not start Excel application - which usually means it is not installed." ; return }
#Call up Excel and tell it to open the file.
try { $excelApp = New-Object -ComObject "Excel.Application" }
catch { Write-Warning "Could not start Excel application - which usually means it is not installed." ; return }

try { $excelWorkBook = $excelApp.Workbooks.Open($Path) }
catch { Write-Warning -Message "Could not Open $Path." ; return }
try { $excelWorkBook = $excelApp.Workbooks.Open($Path) }
catch { Write-Warning -Message "Could not Open $Path." ; return }

#For each worksheet, for each chart, jump to the chart, create a filename of "WorksheetName_ChartTitle.jpg", and export the file.
#For each worksheet, for each chart, jump to the chart, create a filename of "WorksheetName_ChartTitle.jpg", and export the file.
foreach ($excelWorkSheet in $excelWorkBook.Worksheets) {
#note somewhat unusual way of telling excel we want all the charts.
#note somewhat unusual way of telling excel we want all the charts.
foreach ($excelchart in $excelWorkSheet.ChartObjects([System.Type]::Missing)) {
#if you don't go to the chart the image will be zero size !
#if you don't go to the chart the image will be zero size !
$excelApp.Goto($excelchart.TopLeftCell,$true)
$imagePath = Join-Path -Path $Destination -ChildPath ($excelWorkSheet.Name + "_" + ($excelchart.Chart.ChartTitle.Text -split "\s\d\d:\d\d,")[0] + ".$OutputType")
if ( $excelchart.Chart.Export($imagePath, $OutputType, $false) ) { # Export returs true/false for success/failure
if ($Passthru) {Get-Item -Path $imagePath } # when succesful return a file object (-Passthru) or print a verbose message, write warning for any failures
if ( $excelchart.Chart.Export($imagePath, $OutputType, $false) ) { # Export returs true/false for success/failure
if ($Passthru) {Get-Item -Path $imagePath } # when succesful return a file object (-Passthru) or print a verbose message, write warning for any failures
else {Write-Verbose -Message "Exported $imagePath"}
}
else {Write-Warning -Message "Failure exporting $imagePath" }
}
else {Write-Warning -Message "Failure exporting $imagePath" }
}
}
$excelApp.DisplayAlerts = $false
Expand Down
2 changes: 1 addition & 1 deletion Get-ExcelSheetInfo.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Function Get-ExcelSheetInfo {
$stream = New-Object -TypeName System.IO.FileStream -ArgumentList $Path,'Open','Read','ReadWrite'
$xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $stream
$workbook = $xl.Workbook

if ($workbook -and $workbook.Worksheets) {
$workbook.Worksheets |
Select-Object -Property name,index,hidden,@{
Expand Down
30 changes: 15 additions & 15 deletions Get-ExcelWorkbookInfo.ps1
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
Function Get-ExcelWorkbookInfo {
<#
.SYNOPSIS
<#
.SYNOPSIS
Retrieve information of an Excel workbook.
.DESCRIPTION
.DESCRIPTION
The Get-ExcelWorkbookInfo cmdlet retrieves information (LastModifiedBy, LastPrinted, Created, Modified, ...) fron an Excel workbook. These are the same details that are visible in Windows Explorer when right clicking the Excel file, selecting Properties and check the Details tabpage.
.PARAMETER Path
Specifies the path to the Excel file. This parameter is required.
.EXAMPLE
Get-ExcelWorkbookInfo .\Test.xlsx
CorePropertiesXml : #document
Title :
Subject :
Title :
Subject :
Author : Konica Minolta User
Comments :
Keywords :
Comments :
Keywords :
LastModifiedBy : Bond, James (London) GBR
LastPrinted : 2017-01-21T12:36:11Z
Created : 17/01/2017 13:51:32
Category :
Status :
Category :
Status :
ExtendedPropertiesXml : #document
Application : Microsoft Excel
HyperlinkBase :
HyperlinkBase :
AppVersion : 14.0300
Company : Secret Service
Manager :
Manager :
Modified : 10/02/2017 12:45:37
CustomPropertiesXml : #document
Expand All @@ -35,8 +35,8 @@
.LINK
https://github.com/dfinke/ImportExcel
#>
#>

[CmdletBinding()]
Param (
[Alias('FullName')]
Expand All @@ -52,12 +52,12 @@
$xl = New-Object -TypeName OfficeOpenXml.ExcelPackage -ArgumentList $stream
$workbook = $xl.Workbook
$workbook.Properties

$stream.Close()
$stream.Dispose()
$xl.Dispose()
$xl = $null
}
}
Catch {
throw "Failed retrieving Excel workbook information for '$Path': $_"
}
Expand Down
Loading

0 comments on commit e7d2b52

Please sign in to comment.