forked from dfinke/ImportExcel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Export-Excel.ps1
1382 lines (1293 loc) · 75.3 KB
/
Export-Excel.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function Export-Excel {
<#
.SYNOPSIS
Exports data to an Excel worksheet.
.DESCRIPTION
Exports data to an Excel file and where possible tries to convert numbers
in text fields so Excel recognizes them as numbers instead of text.
After all: Excel is a spreadsheet program used for number manipulation
and calculations. If number conversion is not desired, use the
parameter -NoNumberConversion *.
.PARAMETER Path
Path to a new or existing .XLSX file.
.PARAMETER ExcelPackage
An object representing an Excel Package - usually this is returned by specifying -PassThru allowing multiple commands to work on the same workbook without saving and reloading each time.
.PARAMETER WorksheetName
The name of a sheet within the workbook - "Sheet1" by default.
.PARAMETER ClearSheet
If specified Export-Excel will remove any existing worksheet with the selected name. The Default behaviour is to overwrite cells in this sheet as needed (but leaving non-overwritten ones in place).
.PARAMETER Append
If specified dat,a will be added to the end of an existing sheet, using the same column headings.
.PARAMETER TargetData
Data to insert onto the worksheet - this is usually provided from the pipeline.
.PARAMETER DisplayPropertySet
Many (but not all) objects have a hidden property named psStandardmembers with a child property DefaultDisplayPropertySet ; this parameter reduces the properties exported to those in this set.
.PARAMETER NoAliasOrScriptPropeties
Some objects duplicate existing properties by adding aliases, or have Script properties which take a long time to return a value and slow the export down, if specified this removes these properties
.PARAMETER ExcludeProperty
Specifies properties which may exist in the target data but should not be placed on the worksheet.
.PARAMETER Calculate
If specified a recalculation of the worksheet will be requested before saving.
.PARAMETER Title
Text of a title to be placed in the top left cell.
.PARAMETER TitleBold
Sets the title in boldface type.
.PARAMETER TitleSize
Sets the point size for the title.
.PARAMETER TitleBackgroundColor
Sets the cell background color for the title cell.
.PARAMETER TitleFillPattern
Sets the fill pattern for the title cell.
.PARAMETER Password
Sets password protection on the workbook.
.PARAMETER IncludePivotTable
Adds a PivotTable using the data in the worksheet.
.PARAMETER PivotTableName
If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to "WorksheetName-PivotTable".
.PARAMETER PivotRows
Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters.
.PARAMETER PivotColumns
Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters.
.PARAMETER PivotFilter
Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters.
.PARAMETER PivotData
In a PivotTable created from command line parameters, the fields to use in the table body are given as a Hash table in the form ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP.
.PARAMETER PivotDataToColumn
If there are multiple datasets in a PivotTable, by default they are shown as separate rows under the given row heading; this switch makes them separate columns.
.PARAMETER NoTotalsInPivot
In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns.
.PARAMETER PivotTotals
By default, PivotTables have totals for each row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
.PARAMETER PivotTableDefinition
Instead of describing a single PivotTable with multiple command-line parameters; you can use a HashTable in the form PivotTableName = Definition;
Definition is itself a Hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values.
.PARAMETER IncludePivotChart
Include a chart with the PivotTable - implies -IncludePivotTable.
.PARAMETER ChartType
The type for PivotChart (one of Excel's defined chart types).
.PARAMETER NoLegend
Exclude the legend from the PivotChart.
.PARAMETER ShowCategory
Add category labels to the PivotChart.
.PARAMETER ShowPercent
Add percentage labels to the PivotChart.
.PARAMETER ConditionalFormat
One or more conditional formatting rules defined with New-ConditionalFormattingIconSet.
.PARAMETER ConditionalText
Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied.
.PARAMETER NoNumberConversion
By default we convert all values to numbers if possible, but this isn't always desirable. NoNumberConversion allows you to add exceptions for the conversion. Wildcards (like '*') are allowed.
.PARAMETER BoldTopRow
Makes the top row boldface.
.PARAMETER NoHeader
Does not put field names at the top of columns.
.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.
.PARAMETER TableStyle
Selects the style for the named table - defaults to 'Medium6'.
.PARAMETER BarChart
Creates a "quick" bar chart using the first text column as labels and the first numeric column as values
.PARAMETER ColumnChart
Creates a "quick" column chart using the first text column as labels and the first numeric column as values
.PARAMETER LineChart
Creates a "quick" line chart using the first text column as labels and the first numeric column as values
.PARAMETER PieChart
Creates a "quick" pie chart using the first text column as labels and the first numeric column as values
.PARAMETER ExcelChartDefinition
A hash table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-Pivot] charts.
.PARAMETER HideSheet
Name(s) of Sheet(s) to hide in the workbook, supports wildcards. If the selection would cause all sheets to be hidden, the sheet being worked on will be revealed.
.PARAMETER UnHideSheet
Name(s) of Sheet(s) to reveal in the workbook, supports wildcards.
.PARAMETER MoveToStart
If specified, the worksheet will be moved to the start of the workbook.
-MoveToStart takes precedence over -MoveToEnd, -Movebefore and -MoveAfter if more than one is specified.
.PARAMETER MoveToEnd
If specified, the worksheet will be moved to the end of the workbook.
(This is the default position for newly created sheets, but this can be used to move existing sheets.)
.PARAMETER MoveBefore
If specified, the worksheet will be moved before the nominated one (which can be a position starting from 1, or a name).
-MoveBefore takes precedence over -MoveAfter if both are specified.
.PARAMETER MoveAfter
If specified, the worksheet will be moved after the nominated one (which can be a position starting from 1, or a name or *).
If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically.
.PARAMETER KillExcel
Closes Excel - prevents errors writing to the file because Excel has it open.
.PARAMETER AutoNameRange
Makes each column a named range.
.PARAMETER StartRow
Row to start adding data. 1 by default. Row 1 will contain the title if any. Then headers will appear (Unless -No header is specified) then the data appears.
.PARAMETER StartColumn
Column to start adding data - 1 by default.
.PARAMETER FreezeTopRow
Freezes headers etc. in the top row.
.PARAMETER FreezeFirstColumn
Freezes titles etc. in the left column.
.PARAMETER FreezeTopRowFirstColumn
Freezes top row and left column (equivalent to Freeze pane 2,2 ).
.PARAMETER FreezePane
Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber).
.PARAMETER AutoFilter
Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column.
.PARAMETER AutoSize
Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell.
.PARAMETER Activate
If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; if a PivotTable is included it will be the active sheet
.PARAMETER Now
The -Now switch is a shortcut that automatically creates a temporary file, enables "AutoSize", "AutoFiler" and "Show", and opens the file immediately.
.PARAMETER NumberFormat
Formats all values that can be converted to a number to the format specified.
Examples:
# integer (not really needed unless you need to round numbers, Excel will use default cell properties).
'0'
# integer without displaying the number 0 in the cell.
'#'
# number with 1 decimal place.
'0.0'
# number with 2 decimal places.
'0.00'
# number with 2 decimal places and thousand-separator.
'#,##0.00'
# number with 2 decimal places and thousand-separator and money-symbol.
'€#,##0.00'
# percentage (1 = 100%, 0.01 = 1%)
'0%'
# Blue color for positive numbers and a red color for negative numbers. All numbers will be proceeded by a dollar sign '$'.
'[Blue]$#,##0.00;[Red]-$#,##0.00'
.PARAMETER ReZip
If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it.
.PARAMETER NoClobber
Not used. Left in to avoid problems with older scripts, it may be removed in future versions.
.PARAMETER CellStyleSB
A script block which is run at the end of the export to apply styles to cells (although it can be used for other purposes).
The script block is given three paramaters; an object containing the current worksheet, the Total number of Rows and the number of the last column.
.PARAMETER Show
Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first.
.PARAMETER ReturnRange
If specified, Export-Excel returns the range of added cells in the format "A1:Z100".
.PARAMETER PassThru
If specified, Export-Excel returns an object representing the Excel package without saving the package first.
To save, you need to call Close-ExcelPackage or send the object back to Export-Excel, or use its .Save() or SaveAs() method.
.EXAMPLE
Get-Process | Export-Excel .\Test.xlsx -show
Export all the processes to the Excel file 'Test.xlsx' and open the file immediately.
.EXAMPLE
>
PS> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
Write-Output -1 668 34 777 860 -0.5 119 -0.1 234 788 |
Export-Excel @ExcelParams -NumberFormat '[Blue]$#,##0.00;[Red]-$#,##0.00'
Exports all data to the Excel file 'Excel.xslx' and colors the negative values
in Red and the positive values in Blue. It will also add a dollar sign in front
of the numbers which use a thousand seperator and display to two decimal places.
.EXAMPLE
>
PS> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
[PSCustOmobject][Ordered]@{
Date = Get-Date
Formula1 = '=SUM(F2:G2)'
String1 = 'My String'
String2 = 'a'
IPAddress = '10.10.25.5'
Number1 = '07670'
Number2 = '0,26'
Number3 = '1.555,83'
Number4 = '1.2'
Number5 = '-31'
PhoneNr1 = '+32 44'
PhoneNr2 = '+32 4 4444 444'
PhoneNr3 = '+3244444444'
} | Export-Excel @ExcelParams -NoNumberConversion IPAddress, Number1
Exports all data to the Excel file "Excel.xlsx" and tries to convert all values
to numbers where possible except for "IPAddress" and "Number1", which are
stored in the sheet 'as is', without being converted to a number.
.EXAMPLE
>
PS> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
[PSCustOmobject][Ordered]@{
Date = Get-Date
Formula1 = '=SUM(F2:G2)'
String1 = 'My String'
String2 = 'a'
IPAddress = '10.10.25.5'
Number1 = '07670'
Number2 = '0,26'
Number3 = '1.555,83'
Number4 = '1.2'
Number5 = '-31'
PhoneNr1 = '+32 44'
PhoneNr2 = '+32 4 4444 444'
PhoneNr3 = '+3244444444'
} | Export-Excel @ExcelParams -NoNumberConversion *
Exports all data to the Excel file 'Excel.xslx' as is, no number conversion
will take place. This means that Excel will show the exact same data that
you handed over to the 'Export-Excel' function.
.EXAMPLE
>
PS> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
Write-Output 489 668 299 777 860 151 119 497 234 788 |
Export-Excel @ExcelParams -ConditionalText $(
New-ConditionalText -ConditionalType GreaterThan 525 -ConditionalTextColor DarkRed -BackgroundColor LightPink
)
Exports data that will have a Conditional Formatting rule in Excel
that will show cells with a value is greater than 525, whith a
background fill color of "LightPink" and the text in "DarkRed".
Where condition is not met the color willbe the default, black
text on a white background.
.EXAMPLE
>
PS> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
Get-Service | Select-Object -Property Name, Status, DisplayName, ServiceName |
Export-Excel @ExcelParams -ConditionalText $(
New-ConditionalText Stop DarkRed LightPink
New-ConditionalText Running Blue Cyan
)
Exports all services to an Excel sheet, setting a Conditional formatting rule
that will set the background fill color to "LightPink" and the text color
to "DarkRed" when the value contains the word "Stop".
If the value contains the word "Running" it will have a background fill
color of "Cyan" and text colored 'Blue'. If neither condition is met, the
color will be the default, black text on a white background.
.EXAMPLE
>
PS> $ExcelParams = @{
Path = $env:TEMP + '\Excel.xlsx'
Show = $true
Verbose = $true
}
Remove-Item -Path $ExcelParams.Path -Force -EA Ignore
$Array = @()
$Obj1 = [PSCustomObject]@{
Member1 = 'First'
Member2 = 'Second'
}
$Obj2 = [PSCustomObject]@{
Member1 = 'First'
Member2 = 'Second'
Member3 = 'Third'
}
$Obj3 = [PSCustomObject]@{
Member1 = 'First'
Member2 = 'Second'
Member3 = 'Third'
Member4 = 'Fourth'
}
$Array = $Obj1, $Obj2, $Obj3
$Array | Out-GridView -Title 'Not showing Member3 and Member4'
$Array | Update-FirstObjectProperties | Export-Excel @ExcelParams -WorksheetName Numbers
Updates the first object of the array by adding property 'Member3' and 'Member4'.
Afterwards. all objects are exported to an Excel file and all column headers are visible.
.EXAMPLE
Get-Process | Export-Excel .\test.xlsx -WorksheetName Processes -IncludePivotTable -Show -PivotRows Company -PivotData PM
.EXAMPLE
Get-Process | Export-Excel .\test.xlsx -WorksheetName Processes -ChartType PieExploded3D -IncludePivotChart -IncludePivotTable -Show -PivotRows Company -PivotData PM
.EXAMPLE
Get-Service | Export-Excel 'c:\temp\test.xlsx' -Show -IncludePivotTable -PivotRows status -PivotData @{status='count'}
.EXAMPLE
>
PS> $pt = [ordered]@{}
$pt.pt1=@{ SourceWorkSheet = 'Sheet1';
PivotRows = 'Status'
PivotData = @{'Status'='count'}
IncludePivotChart = $true
ChartType = 'BarClustered3D'
}
$pt.pt2=@{ SourceWorkSheet = 'Sheet2';
PivotRows = 'Company'
PivotData = @{'Company'='count'}
IncludePivotChart = $true
ChartType = 'PieExploded3D'
}
Remove-Item -Path .\test.xlsx
Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -AutoSize
Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .\test.xlsx -AutoSize -WorksheetName 'sheet2'
Export-Excel -Path .\test.xlsx -PivotTableDefinition $pt -Show
This example defines two PivotTables. Then it puts Service data on Sheet1
with one call to Export-Excel and Process Data on sheet2 with a second
call to Export-Excel. The third and final call adds the two PivotTables
and opens the spreadsheet in Excel.
.EXAMPLE
>
PS> Remove-Item -Path .\test.xlsx
$excel = Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .\test.xlsx -PassThru
$excel.Workbook.Worksheets["Sheet1"].Row(1).style.font.bold = $true
$excel.Workbook.Worksheets["Sheet1"].Column(3 ).width = 29
$excel.Workbook.Worksheets["Sheet1"].Column(3 ).Style.wraptext = $true
$excel.Save()
$excel.Dispose()
Start-Process .\test.xlsx
This example uses -PassThru. It puts service information into sheet1 of the
workbook and saves the ExcelPackage object in $Excel. It then uses the package
object to apply formatting, and then saves the workbook and disposes of the object
before loading the document in Excel. Other commands in the module remove the need
to work directly with the package object in this way.
.EXAMPLE
>
PS> Remove-Item -Path .\test.xlsx -ErrorAction Ignore
$excel = Get-Process | Select-Object -Property Name,Company,Handles,CPU,PM,NPM,WS | Export-Excel -Path .\test.xlsx -ClearSheet -WorksheetName "Processes" -PassThru
$sheet = $excel.Workbook.Worksheets["Processes"]
$sheet.Column(1) | Set-ExcelRange -Bold -AutoFit
$sheet.Column(2) | Set-ExcelRange -Width 29 -WrapText
$sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NFormat "#,###"
Set-ExcelRange -Address $sheet.Cells["E1:H1048576"] -HorizontalAlignment Right -NFormat "#,###"
Set-ExcelRange -Address $sheet.Column(4) -HorizontalAlignment Right -NFormat "#,##0.0" -Bold
Set-ExcelRange -Address $sheet.Row(1) -Bold -HorizontalAlignment Center
Add-ConditionalFormatting -WorkSheet $sheet -Range "D2:D1048576" -DataBarColor Red
Add-ConditionalFormatting -WorkSheet $sheet -Range "G2:G1048576" -RuleType GreaterThan -ConditionValue "104857600" -ForeGroundColor Red
foreach ($c in 5..9) {Set-ExcelRange -Address $sheet.Column($c) -AutoFit }
Export-Excel -ExcelPackage $excel -WorksheetName "Processes" -IncludePivotChart -ChartType ColumnClustered -NoLegend -PivotRows company -PivotData @{'Name'='Count'} -Show
This a more sophisticated version of the previous example showing different
ways of using Set-ExcelRange, and also adding conditional formatting.
In the final command a PivotChart is added and the workbook is opened in Excel.
.EXAMPLE
0..360 | ForEach-Object {[pscustomobject][ordered]@{X=$_; Sinx="=Sin(Radians(x)) "} } | Export-Excel -now -LineChart -AutoNameRange
Creates a line chart showing the value of Sine(x) for values of X between 0 and 360 degrees.
.EXAMPLE
>
PS> Invoke-Sqlcmd -ServerInstance localhost\DEFAULT -Database AdventureWorks2014 -Query "select * from sys.tables" -OutputAs DataRows |
Export-Excel -Path .\SysTables_AdventureWorks2014.xlsx -WorksheetName Tables
Runs a query against a SQL Server database and outputs the resulting rows DataRows using the -OutputAs parameter.
The results are then piped to the Export-Excel function.
NOTE: You need to install the SqlServer module from the PowerShell Gallery in oder to get the -OutputAs parameter for the Invoke-Sqlcmd cmdlet.
.LINK
https://github.com/dfinke/ImportExcel
#>
[CmdletBinding(DefaultParameterSetName = 'Default')]
[OutputType([OfficeOpenXml.ExcelPackage])]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
Param(
[Parameter(ParameterSetName = "Default", Position = 0)]
[Parameter(ParameterSetName = "Table" , Position = 0)]
[String]$Path,
[Parameter(Mandatory = $true, ParameterSetName = "PackageDefault")]
[Parameter(Mandatory = $true, ParameterSetName = "PackageTable")]
[OfficeOpenXml.ExcelPackage]$ExcelPackage,
[Parameter(ValueFromPipeline = $true)]
$TargetData,
[Switch]$Calculate,
[Switch]$Show,
[String]$WorksheetName = 'Sheet1',
[String]$Password,
[switch]$ClearSheet,
[switch]$Append,
[String]$Title,
[OfficeOpenXml.Style.ExcelFillStyle]$TitleFillPattern = 'Solid',
[Switch]$TitleBold,
[Int]$TitleSize = 22,
$TitleBackgroundColor,
[Switch]$IncludePivotTable,
[String]$PivotTableName,
[String[]]$PivotRows,
[String[]]$PivotColumns,
$PivotData,
[String[]]$PivotFilter,
[Switch]$PivotDataToColumn,
[Hashtable]$PivotTableDefinition,
[Switch]$IncludePivotChart,
[OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = 'Pie',
[Switch]$NoLegend,
[Switch]$ShowCategory,
[Switch]$ShowPercent,
[Switch]$AutoSize,
[Switch]$NoClobber,
[Switch]$FreezeTopRow,
[Switch]$FreezeFirstColumn,
[Switch]$FreezeTopRowFirstColumn,
[Int[]]$FreezePane,
[Parameter(ParameterSetName = 'Default')]
[Parameter(ParameterSetName = 'PackageDefault')]
[Switch]$AutoFilter,
[Switch]$BoldTopRow,
[Switch]$NoHeader,
[ValidateScript( {
if (-not $_) { throw 'RangeName is null or empty.' }
elseif ($_[0] -notmatch '[a-z]') { throw 'RangeName starts with an invalid character.' }
else { $true }
})]
[String]$RangeName,
[ValidateScript( {
if (-not $_) { throw 'Tablename is null or empty.' }
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 = 'Medium6',
[Switch]$Barchart,
[Switch]$PieChart,
[Switch]$LineChart ,
[Switch]$ColumnChart ,
[Object[]]$ExcelChartDefinition,
[String[]]$HideSheet,
[String[]]$UnHideSheet,
[Switch]$MoveToStart,
[Switch]$MoveToEnd,
$MoveBefore ,
$MoveAfter ,
[Switch]$KillExcel,
[Switch]$AutoNameRange,
[Int]$StartRow = 1,
[Int]$StartColumn = 1,
[Switch]$PassThru,
[String]$Numberformat = 'General',
[string[]]$ExcludeProperty,
[Switch]$NoAliasOrScriptPropeties,
[Switch]$DisplayPropertySet,
[String[]]$NoNumberConversion,
[Object[]]$ConditionalFormat,
[Object[]]$ConditionalText,
[ScriptBlock]$CellStyleSB,
#If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified
[switch]$Activate,
[Parameter(ParameterSetName = 'Now')]
[Switch]$Now,
[Switch]$ReturnRange,
#By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
[ValidateSet("Both","Columns","Rows","None")]
[String]$PivotTotals = "Both",
#Included for compatibility - equivalent to -PivotTotals "None"
[Switch]$NoTotalsInPivot,
[Switch]$ReZip
)
Begin {
$numberRegex = [Regex]'\d'
function Add-CellValue {
<#
.SYNOPSIS
Save a value in an Excel cell.
.DESCRIPTION
DateTime objects are always converted to a short DateTime format in Excel. When Excel loads the file,
it applies the local format for dates. And formulas are always saved as formulas. URIs are set as hyperlinks in the file.
Numerical values will be converted to numbers as defined in the regional settings of the local
system. In case the parameter 'NoNumberConversion' is used, we don't convert to number and leave
the value 'as is'. In case of conversion failure, we also leave the value 'as is'.
#>
Param (
$TargetCell,
$CellValue
)
#The write-verbose commands have been commented out below - even if verbose is silenced they cause a significiant performance impact and if it's on they will cause a flood of messages.
Switch ($CellValue) {
{ $_ -is [DateTime]} {
# Save a date with one of Excel's built in formats format
$TargetCell.Value = $_
$TargetCell.Style.Numberformat.Format = 'm/d/yy h:mm' # This is not a custom format, but a preset recognized as date and localized.
#Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$_' as date"
break
}
{ $_ -is [TimeSpan]} {
#Save a timespans with a built in format for elapsed hours, minutes and seconds
$TargetCell.Value = $_
$TargetCell.Style.Numberformat.Format = '[h]:mm:ss'
break
}
{ $_ -is [System.ValueType]} {
# Save numerics, setting format if need be.
$TargetCell.Value = $_
if ($setNumformat) {$targetCell.Style.Numberformat.Format = $Numberformat }
#Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$_' as value"
break
}
{($_ -is [String]) -and ($_[0] -eq '=')} {
#region Save an Excel formula - we need = to spot the formula but the EPPLUS won't like it if we include it (Excel doesn't care if is there or not)
$TargetCell.Formula = ($_ -replace '^=','')
if ($setNumformat) {$targetCell.Style.Numberformat.Format = $Numberformat }
#Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$_' as formula"
break
}
{ [System.Uri]::IsWellFormedUriString($_ , [System.UriKind]::Absolute) } {
# Save a hyperlink : internal links can be in the form xl://sheet!E419 (use A1 as goto sheet), or xl://RangeName
if ($_ -is [uri]) {$targetCell.HyperLink = $_ }
elseif ($_ -match "^xl://internal/") {
$referenceAddress = $_ -replace "^xl://internal/" , ""
$display = $referenceAddress -replace "!A1$" , ""
$h = New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList $referenceAddress , $display
$TargetCell.HyperLink = $h
}
else {$TargetCell.HyperLink = $_ } #$TargetCell.Value = $_.AbsoluteUri
$TargetCell.Style.Font.Color.SetColor([System.Drawing.Color]::Blue)
$TargetCell.Style.Font.UnderLine = $true
#Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$($_.AbsoluteUri)' as Hyperlink"
break
}
{( $NoNumberConversion -and (
($NoNumberConversion -contains $Name) -or ($NoNumberConversion -eq '*'))) } {
#Save text without it to converting to number
$TargetCell.Value = $_
#Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$($TargetCell.Value)' unconverted"
break
}
Default {
#Save a value as a number if possible
$number = $null
if ($numberRegex.IsMatch($_) -and [Double]::TryParse($_, [System.Globalization.NumberStyles]::Any, [System.Globalization.NumberFormatInfo]::CurrentInfo, [Ref]$number)) {
# as simpler version using [Double]::TryParse( $_ , [ref]$number)) was found to cause problems reverted back to the longer version
$TargetCell.Value = $number
if ($setNumformat) {$targetCell.Style.Numberformat.Format = $Numberformat }
#Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$($TargetCell.Value)' as number converted from '$_' with format '$Numberformat'"
}
else {
$TargetCell.Value = $_
#Write-Verbose "Cell '$Row`:$ColumnIndex' header '$Name' add value '$($TargetCell.Value)' as string"
}
break
}
}
}
try {
$script:Header = $null
if ($Append -and $ClearSheet) {throw "You can't use -Append AND -ClearSheet."}
if ($PSBoundParameters.Keys.Count -eq 0 -Or $Now) {
$Path = [System.IO.Path]::GetTempFileName() -replace '\.tmp', '.xlsx'
$Show = $true
$AutoSize = $true
if (!$TableName) {
$AutoFilter = $true
}
}
if ($ExcelPackage) {
$pkg = $ExcelPackage
$Path = $pkg.File
}
Else { $pkg = Open-ExcelPackage -Path $Path -Create -KillExcel:$KillExcel -Password:$Password}
}
catch {throw "Could not open Excel Package $path"}
if ($NoClobber) {Write-Warning -Message "-NoClobber parameter is no longer used" }
try {
$params = @{WorksheetName=$WorksheetName}
foreach ($p in @("ClearSheet", "MoveToStart", "MoveToEnd", "MoveBefore", "MoveAfter", "Activate")) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}}
$ws = $pkg | Add-WorkSheet @params
if ($ws.Name -ne $WorksheetName) {
Write-Warning -Message "The Worksheet name has been changed from $WorksheetName to $($ws.Name), this may cause errors later."
$WorksheetName = $ws.Name
}
}
catch {throw "Could not get worksheet $worksheetname"}
try {
if ($Append -and $ws.Dimension) {
#if there is a title or anything else above the header row, append needs to be combined wih a suitable startrow parameter
$headerRange = $ws.Dimension.Address -replace "\d+$", $StartRow
#using a slightly odd syntax otherwise header ends up as a 2D array
$ws.Cells[$headerRange].Value | ForEach-Object -Begin {$Script:header = @()} -Process {$Script:header += $_ }
#if we did not get AutoNameRange, but headers have ranges of the same name make autoNameRange True, otherwise make it false
if (-not $AutoNameRange) {
$AutoNameRange = $true ; foreach ($h in $header) {if ($ws.names.name -notcontains $h) {$AutoNameRange = $false} }
}
#if we did not get a Rangename but there is a Range which covers the active part of the sheet, set Rangename to that.
if (-not $RangeName -and $ws.names.where({$_.name[0] -match '[a-z]'})) {
$theRange = $ws.names.where({
($_.Name[0] -match '[a-z]' ) -and
($_.Start.Row -eq $StartRow) -and
($_.Start.Column -eq $StartColumn) -and
($_.End.Row -eq $ws.Dimension.End.Row) -and
($_.End.Column -eq $ws.Dimension.End.column) } , 'First', 1)
if ($theRange) {$rangename = $theRange.name}
}
#if we did not get a table name but there is a table which covers the active part of the sheet, set table name to that, and don't do anything with autofilter
if (-not $TableName -and $ws.Tables.Where({$_.address.address -eq $ws.dimension.address})) {
$TableName = $ws.Tables.Where({$_.address.address -eq $ws.dimension.address},'First', 1).Name
$AutoFilter = $false
}
#if we did not get $autofilter but a filter range is set and it covers the right area, set autofilter to true
elseif (-not $AutoFilter -and $ws.Names['_xlnm._FilterDatabase']) {
if ( ($ws.Names['_xlnm._FilterDatabase'].Start.Row -eq $StartRow) -and
($ws.Names['_xlnm._FilterDatabase'].Start.Column -eq $StartColumn) -and
($ws.Names['_xlnm._FilterDatabase'].End.Row -eq $ws.Dimension.End.Row) -and
($ws.Names['_xlnm._FilterDatabase'].End.Column -eq $ws.Dimension.End.Column) ) {$AutoFilter = $true}
}
$row = $ws.Dimension.End.Row
Write-Debug -Message ("Appending: headers are " + ($script:Header -join ", ") + " Start row is $row")
}
elseif ($Title) {
#Can only add a title if not appending!
$Row = $StartRow
$ws.Cells[$Row, $StartColumn].Value = $Title
$ws.Cells[$Row, $StartColumn].Style.Font.Size = $TitleSize
if ($TitleBold) {
#Set title to Bold face font if -TitleBold was specified.
#Otherwise the default will be unbolded.
$ws.Cells[$Row, $StartColumn].Style.Font.Bold = $True
}
if ($TitleBackgroundColor ) {
if ($TitleBackgroundColor -is [string]) {$TitleBackgroundColor = [System.Drawing.Color]::$TitleBackgroundColor }
$ws.Cells[$Row, $StartColumn].Style.Fill.PatternType = $TitleFillPattern
$ws.Cells[$Row, $StartColumn].Style.Fill.BackgroundColor.SetColor($TitleBackgroundColor)
}
$Row ++ ; $startRow ++
}
else { $Row = $StartRow }
$ColumnIndex = $StartColumn
$Numberformat = Expand-NumberFormat -NumberFormat $Numberformat
if ((-not $ws.Dimension) -and ($Numberformat -ne $ws.Cells.Style.Numberformat.Format)) {
$ws.Cells.Style.Numberformat.Format = $Numberformat
$setNumformat = $false
}
else { $setNumformat = ($Numberformat -ne $ws.Cells.Style.Numberformat.Format) }
$firstTimeThru = $true
$isDataTypeValueType = $false
}
catch {
if ($AlreadyExists) {
#Is this set anywhere ?
throw "Failed exporting worksheet '$WorksheetName' to '$Path': The worksheet '$WorksheetName' already exists."
}
else {
throw "Failed preparing to export to worksheet '$WorksheetName' to '$Path': $_"
}
}
}
Process {
if ($PSBoundParameters.ContainsKey("TargetData")) {
try {
if ($firstTimeThru) {
$firstTimeThru = $false
$isDataTypeValueType = ($null -eq $TargetData) -or ($TargetData.GetType().name -match 'string|timespan|datetime|bool|byte|char|decimal|double|float|int|long|sbyte|short|uint|ulong|ushort|URI|ExcelHyperLink')
if ($isDataTypeValueType -and -not $Append) {$row -= 1} #row incremented before adding values, so it is set to the number of rows inserted at the end
if ($null -ne $TargetData) {Write-Debug "DataTypeName is '$($TargetData.GetType().name)' isDataTypeValueType '$isDataTypeValueType'" }
}
if ($isDataTypeValueType) {
$ColumnIndex = $StartColumn
$Row += 1
try {Add-CellValue -TargetCell $ws.Cells[$Row, $ColumnIndex] -CellValue $TargetData}
catch {Write-Warning "Could not insert value at Row $Row. "}
}
else {
#region Add headers - if we are appending, or we have been through here once already we will have the headers
if (-not $script:Header) {
$ColumnIndex = $StartColumn
if ($DisplayPropertySet -and $TargetData.psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames) {
$script:Header = $TargetData.psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Where( {$_ -notin $ExcludeProperty})
}
else {
if ($NoAliasOrScriptPropeties) {$propType = "Property"} else {$propType = "*"}
$script:Header = $TargetData.PSObject.Properties.where( {$_.MemberType -like $propType}).Name
}
foreach ($exclusion in $ExcludeProperty) {$script:Header = $script:Header -notlike $exclusion}
if ($NoHeader) {
# Don't push the headers to the spreadsheet
$Row -= 1
}
else {
foreach ($Name in $script:Header) {
$ws.Cells[$Row, $ColumnIndex].Value = $Name
Write-Verbose "Cell '$Row`:$ColumnIndex' add header '$Name'"
$ColumnIndex += 1
}
}
}
#endregion
#region Add non header values
$Row += 1
$ColumnIndex = $StartColumn
foreach ($Name in $script:Header) {
try {Add-CellValue -TargetCell $ws.Cells[$Row, $ColumnIndex] -CellValue $TargetData.$Name}
catch {Write-Warning -Message "Could not insert the '$Name' property at Row $Row, Column $ColumnIndex"}
$ColumnIndex += 1
}
$ColumnIndex -= 1 # column index will be the last column whether isDataTypeValueType was true or false
#endregion
}
}
catch {
throw "Failed exporting data to worksheet '$WorksheetName' to '$Path': $_"
}
}
}
End {
if ($firstTimeThru -and $ws.Dimension) {
$LastRow = $ws.Dimension.End.Row
$LastCol = $ws.Dimension.End.Column
$endAddress = $ws.Dimension.End.Address
}
else {
$LastRow = $Row
$LastCol = $ColumnIndex
$endAddress = [OfficeOpenXml.ExcelAddress]::GetAddress($LastRow , $LastCol)
}
$startAddress = [OfficeOpenXml.ExcelAddress]::GetAddress($StartRow, $StartColumn)
$dataRange = "{0}:{1}" -f $startAddress, $endAddress
Write-Debug "Data Range '$dataRange'"
if ($AutoNameRange) {
try {
if (-not $script:header) {
# if there aren't any headers, use the the first row of data to name the ranges: this is the last point that headers will be used.
$headerRange = $ws.Dimension.Address -replace "\d+$", $StartRow
#using a slightly odd syntax otherwise header ends up as a 2D array
$ws.Cells[$headerRange].Value | ForEach-Object -Begin {$Script:header = @()} -Process {$Script:header += $_ }
if ($PSBoundParameters.ContainsKey($TargetData)) { #if Export was called with data that writes no header start the range at $startRow ($startRow is data)
$targetRow = $StartRow
}
else { $targetRow = $StartRow + 1 } #if Export was called without data to add names (assume $startRow is a header) or...
} # ... called with data that writes a header, then start the range at $startRow + 1
else { $targetRow = $StartRow + 1 }
#Dimension.start.row always seems to be one so we work out the target row
#, but start.column is the first populated one and .Columns is the count of populated ones.
# if we have 5 columns from 3 to 8, headers are numbered 0..4, so that is in the for loop and used for getting the name...
# but we have to add the start column on when referencing positions
foreach ($c in 0..($LastCol - $StartColumn)) {
$targetRangeName = $script:Header[$c] #Let Add-ExcelName fix (and warn about) bad names
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."
}
} Catch {}
}
}
catch {Write-Warning -Message "Failed adding named ranges to worksheet '$WorksheetName': $_" }
}
if ($RangeName) { Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $RangeName}
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) {
try {
$ws.Cells[$dataRange].AutoFilter = $true
Write-Verbose -Message "Enabled autofilter. "
}
catch {Write-Warning -Message "Failed adding autofilter to worksheet '$WorksheetName': $_"}
}
if ($PivotTableDefinition) {
foreach ($item in $PivotTableDefinition.GetEnumerator()) {
$params = $item.value
if ($Activate) {$params.Activate = $true }
if ($params.keys -notcontains 'SourceRange' -and
($params.Keys -notcontains 'SourceWorkSheet' -or $params.SourceWorkSheet -eq $WorksheetName)) {$params.SourceRange = $dataRange}
if ($params.Keys -notcontains 'SourceWorkSheet') {$params.SourceWorkSheet = $ws }
if ($params.Keys -notcontains 'NoTotalsInPivot' -and $NoTotalsInPivot ) {$params.PivotTotals = 'None'}
if ($params.Keys -notcontains 'PivotTotals' -and $PivotTotals ) {$params.PivotTotals = $PivotTotals}
if ($params.Keys -notcontains 'PivotDataToColumn' -and $PivotDataToColumn) {$params.PivotDataToColumn = $true}
Add-PivotTable -ExcelPackage $pkg -PivotTableName $item.key @Params
}
}
if ($IncludePivotTable -or $IncludePivotChart) {
$params = @{
'SourceRange' = $dataRange
}
if ($PivotTableName -and ($pkg.workbook.worksheets.tables.name -contains $PivotTableName)) {
Write-Warning -Message "The selected PivotTable name '$PivotTableName' is already used as a table name. Adding a suffix of 'Pivot'."
$PivotTableName += 'Pivot'
}
if ($PivotTableName) {$params.PivotTableName = $PivotTableName}
else {$params.PivotTableName = $WorksheetName + 'PivotTable'}
if ($Activate) {$params.Activate = $true }
if ($PivotFilter) {$params.PivotFilter = $PivotFilter}
if ($PivotRows) {$params.PivotRows = $PivotRows}
if ($PivotColumns) {$Params.PivotColumns = $PivotColumns}
if ($PivotData) {$Params.PivotData = $PivotData}
if ($NoTotalsInPivot) {$params.PivotTotals = "None" }
Elseif ($PivotTotals) {$params.PivotTotals = $PivotTotals}
if ($PivotDataToColumn) {$params.PivotDataToColumn = $true}
if ($IncludePivotChart) {
$params.IncludePivotChart = $true
$Params.ChartType = $ChartType
if ($ShowCategory) {$params.ShowCategory = $true}
if ($ShowPercent) {$params.ShowPercent = $true}
if ($NoLegend) {$params.NoLegend = $true}
}
Add-PivotTable -ExcelPackage $pkg -SourceWorkSheet $ws @params
}
try {
#Allow single switch or two seperate ones.
if ($FreezeTopRowFirstColumn -or ($FreezeTopRow -and $FreezeFirstColumn)) {
$ws.View.FreezePanes(2, 2)
Write-Verbose -Message "Froze top row and first column"
}
elseif ($FreezeTopRow) {
$ws.View.FreezePanes(2, 1)
Write-Verbose -Message "Froze top row"
}
elseif ($FreezeFirstColumn) {
$ws.View.FreezePanes(1, 2)
Write-Verbose -Message "Froze first column"
}
if ($FreezePane) {
$freezeRow, $freezeColumn = $FreezePane
if (-not $freezeColumn -or $freezeColumn -eq 0) {
$freezeColumn = 1
}
if ($freezeRow -gt 1) {
$ws.View.FreezePanes($freezeRow, $freezeColumn)
Write-Verbose -Message "Froze pandes at row $freezeRow and column $FreezeColumn"
}
}
}
catch {Write-Warning -Message "Failed adding Freezing the panes in worksheet '$WorksheetName': $_"}
if ($BoldTopRow) { #it sets bold as far as there are populated cells: for whole row could do $ws.row($x).style.font.bold = $true
try {
if ($Title) {
$range = $ws.Dimension.Address -replace '\d+', ($StartRow + 1)
}
else {
$range = $ws.Dimension.Address -replace '\d+', $StartRow
}
$ws.Cells[$range].Style.Font.Bold = $true
Write-Verbose -Message "Set $range font style to bold."
}
catch {Write-Warning -Message "Failed setting the top row to bold in worksheet '$WorksheetName': $_"}
}
if ($AutoSize) {
try {
$ws.Cells.AutoFitColumns()
Write-Verbose -Message "Auto-sized columns"
}
catch { Write-Warning -Message "Failed autosizing columns of worksheet '$WorksheetName': $_"}
}
foreach ($Sheet in $HideSheet) {
try {
$pkg.Workbook.WorkSheets.Where({$_.Name -like $sheet}) | ForEach-Object {
$_.Hidden = 'Hidden'
Write-verbose -Message "Sheet '$($_.Name)' Hidden."
}
}
catch {Write-Warning -Message "Failed hiding worksheet '$sheet': $_"}
}
foreach ($Sheet in $UnHideSheet) {
try {
$pkg.Workbook.WorkSheets.Where({$_.Name -like $sheet}) | ForEach-Object {
$_.Hidden = 'Visible'
Write-verbose -Message "Sheet '$($_.Name)' shown"
}
}
catch {Write-Warning -Message "Failed showing worksheet '$sheet': $_"}
}
if (-not $pkg.Workbook.Worksheets.Where({$_.Hidden -eq 'visible'})) {
Write-Verbose -Message "No Sheets were left visible, making $WorksheetName visible"
$ws.Hidden = 'Visible'
}
foreach ($chartDef in $ExcelChartDefinition) {
if ($chartDef -is [System.Management.Automation.PSCustomObject]) {
$params = @{}
$chartDef.PSObject.Properties | ForEach-Object {if ( $null -ne $_.value) {$params[$_.name] = $_.value}}
Add-ExcelChart -Worksheet $ws @params
}
elseif ($chartDef -is [hashtable] -or $chartDef -is[System.Collections.Specialized.OrderedDictionary]) {
Add-ExcelChart -Worksheet $ws @chartDef
}
}
if ($Calculate) {
try { [OfficeOpenXml.CalculationExtension]::Calculate($ws) }
catch { Write-Warning "One or more errors occured while calculating, save will continue, but there may be errors in the workbook. $_"}
}
if ($Barchart -or $PieChart -or $LineChart -or $ColumnChart) {
if ($NoHeader) {$FirstDataRow = $startRow}
else {$FirstDataRow = $startRow + 1 }
$range = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $startColumn, $FirstDataRow, $lastCol )
$xCol = $ws.cells[$range] | Where-Object {$_.value -is [string] } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1
if (-not $xcol) {
$xcol = $StartColumn
$range = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, ($startColumn +1), $FirstDataRow, $lastCol )
}
$yCol = $ws.cells[$range] | Where-Object {$_.value -is [valueType] -or $_.Formula } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1
if (-not ($xCol -and $ycol)) { Write-Warning -Message "Can't identify a string column and a number column to use as chart labels and data. "}
else {
$params = @{
XRange = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $xcol , $lastrow, $xcol)
YRange = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $ycol , $lastrow, $ycol)
Title = ''
Column = ($lastCol +1)
Width = 800
}
if ($ShowPercent) {$params["ShowPercent"] = $true}
if ($ShowCategory) {$params["ShowCategory"] = $true}
if ($NoLegend) {$params["NoLegend"] = $true}
if (-not $NoHeader) {$params["SeriesHeader"] = $ws.Cells[$startRow, $YCol].Value}
if ($ColumnChart) {$Params["chartType"] = "ColumnStacked" }
elseif ($Barchart) {$Params["chartType"] = "BarStacked" }
elseif ($PieChart) {$Params["chartType"] = "PieExploded3D" }
elseif ($LineChart) {$Params["chartType"] = "Line" }
Add-ExcelChart -Worksheet $ws @params