Format-Cell.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
function Format-Cell {
    <#
    .SYNOPSIS
        Format cells in an Excel worksheet
 
    .DESCRIPTION
        Format cells in an Excel worksheet
 
        Note:
            Each time you call this function, you need to save and re-create your Excel Object.
            If you attempt to modify the Excel object, save, modify, and save a second time, it will fail.
            See Save-Excel Passthru parameter for a workaround
         
    .PARAMETER Worksheet
        Worksheet to format cells on
     
    .PARAMETER StartRow
        The top row to format. If not specified, we use the dimensions start row
 
    .PARAMETER StartColumn
        The leftmost column to format. If not specified, we use the dimensions start column
 
    .PARAMETER EndRow
        The bottom row to format. If not specified, we use the dimensions' end row
 
    .PARAMETER EndColumn
        The rightmost column to format. If not specified, we use the dimensions' end column
 
    .PARAMETER Header
        If specified, identify and apply formatting to the header row only.
 
    .PARAMETER Bold
        Add or remove bold font (boolean)
 
    .PARAMETER Italic
        Add or remove Italic font (boolean)
 
    .PARAMETER Underline
        Add or remove Underline font (boolean)
 
    .PARAMETER Size
        Set font size
 
    .PARAMETER Font
        Set font name
         
    .PARAMETER Color
        Set font color
 
    .PARAMETER BackgroundColor
        Set background fill color
 
    .PARAMETER FillStyle
        Set the FillStyle, if BackgroundColor is specified. Default is Solid
 
    .PARAMETER WrapText
        Add or remove WrapText property (boolean)
 
    .PARAMETER AutoFilter
        Set autofilter for the cells
 
        This currently only works for $True. It won't turn off Autofilter with $False.
 
    .PARAMETER AutoFit
        Apply auto fit to cells
 
    .PARAMETER AutoFitMinWidth
        Minimum width to set autofit with
     
    .PARAMETER AutoFitMaxWidth
        Maximum width to set autofit with
 
    .PARAMETER VerticalAlignment
        Set the vertical alignment
 
    .PARAMETER HorizontalAlignment
        Set the horizontal alignment
 
    .PARAMETER Border
        Set a border to the left, right, top, bottom, or all (*).
 
    .PARAMETER BorderStyle
        Style for the border. Defaults to Thin
 
    .PARAMETER BorderColor
        Color for the border. Defaults to Black
 
    .PARAMETER Passthru
        If specified, pass the Worksheet back
 
    .EXAMPLE
        #
        # Create an Excel object to work with
            $Excel = New-Excel -Path C:\Temp\Demo.xlsx
         
        #Get the worksheet, format the header as bold, size 14
            $Excel |
                Get-WorkSheet |
                Format-Cell -Header -Bold $True -Size 14
         
        #Save your changes, re-open the excel file
            $Excel = $Excel | Save-Excel -Passthru
 
        #Oops, too big! Get the worksheet, format the header as size 11
            $Excel |
                Get-WorkSheet |
                Format-Cell -Header -Size 11
 
            $Excel | Save-Excel -Close
 
    .EXAMPLE
        $WorkSheet | Format-Cell -StartRow 2 -StartColumn 1 -EndColumn 1 -Italic $True -Size 10
 
        # Set the first column, rows 2 through the end to size 10, italic
 
    .EXAMPLE
           
        # Get the worksheet
        # format all the cells (default if nothing specified)
        # Set autofit between minumum of 5 and maximum of 20
        $Excel |
            Get-WorkSheet |
            Format-Cell -Autofit -AutofitMinWidth 5 -AutofitMaxWidth 20
 
    .NOTES
        Thanks to Doug Finke for his example:
            https://github.com/dfinke/ImportExcel/blob/master/ImportExcel.psm1
 
        Thanks to Philip Thompson for an expansive set of examples on working with EPPlus in PowerShell:
            https://excelpslib.codeplex.com/
 
    .LINK
        https://github.com/RamblingCookieMonster/PSExcel
 
    .FUNCTIONALITY
        Excel
    #>

    [OutputType([OfficeOpenXml.ExcelWorksheet])]
    [cmdletbinding(DefaultParameterSetname = 'Range')]
    param(
        [parameter( Mandatory=$true,
                    ValueFromPipeline=$true,
                    ValueFromPipelineByPropertyName=$true)]
        [OfficeOpenXml.ExcelWorksheet]$WorkSheet,

        [parameter( ParameterSetName = 'Range',
                    Mandatory=$false,
                    ValueFromPipeline=$false,
                    ValueFromPipelineByPropertyName=$false)]
        [int]$StartRow,
        
        [parameter( ParameterSetName = 'Range',
                    Mandatory=$false,
                    ValueFromPipeline=$false,
                    ValueFromPipelineByPropertyName=$false)]
        [int]$StartColumn,
        
        [parameter( ParameterSetName = 'Range',
                    Mandatory=$false,
                    ValueFromPipeline=$false,
                    ValueFromPipelineByPropertyName=$false)]
        [int]$EndRow,

        [parameter( ParameterSetName = 'Range',
                    Mandatory=$false,
                    ValueFromPipeline=$false,
                    ValueFromPipelineByPropertyName=$false)]
        [int]$EndColumn,

        [parameter( ParameterSetName = 'Header',
                    Mandatory=$true,
                    ValueFromPipeline=$false,
                    ValueFromPipelineByPropertyName=$false)]
        [Switch]$Header,

        [boolean]$Bold,
        [boolean]$Italic,
        [boolean]$Underline,
        [int]$Size,
        [string]$Font,
        
        [System.Drawing.KnownColor]$Color,
        [System.Drawing.KnownColor]$BackgroundColor,
        [OfficeOpenXml.Style.ExcelFillStyle]$FillStyle,
        [boolean]$WrapText,
        [String]$NumberFormat,

        [boolean]$AutoFilter,
        [switch]$Autofit,
        [double]$AutofitMinWidth,
        [double]$AutofitMaxWidth,

        [OfficeOpenXml.Style.ExcelVerticalAlignment]$VerticalAlignment,
        [OfficeOpenXml.Style.ExcelHorizontalAlignment]$HorizontalAlignment,

        [validateset('Left','Right','Top','Bottom','*')]
        [string[]]$Border,
        [OfficeOpenXml.Style.ExcelBorderStyle]$BorderStyle,
        [System.Drawing.KnownColor]$BorderColor,

        [switch]$Passthru
    )
    Begin
    {

        if($PSBoundParameters.ContainsKey('BorderColor'))
        {
            Try
            {
                $BorderColorConverted = [System.Drawing.Color]::FromKnownColor($BorderColor)
            }
            Catch
            {
                Throw "Failed to convert $($BorderColor) to a valid System.Drawing.Color: $_"
            }
        }

        if($PSBoundParameters.ContainsKey('Color'))
        {
            Try
            {
                $ColorConverted = [System.Drawing.Color]::FromKnownColor($Color)
            }
            Catch
            {
                Throw "Failed to convert $($Color) to a valid System.Drawing.Color: $_"
            }
        }

        if($PSBoundParameters.ContainsKey('BackgroundColor'))
        {
            Try
            {
                $BackgroundColorConverted = [System.Drawing.Color]::FromKnownColor($BackgroundColor)
                if(-not $PSBoundParameters.ContainsKey('FillStyle'))
                {
                    $FillStyle = [OfficeOpenXml.Style.ExcelFillStyle]::Solid
                }
            }
            Catch
            {
                Throw "Failed to convert $($BackgroundColor) to a valid System.Drawing.Color: $_"
            }
        }
    }
    Process
    {
        #Get the coordinates
            $dimension = $WorkSheet.Dimension
        
            if($PSCmdlet.ParameterSetName -like 'Range')
            {
                If(-not $StartRow)
                {
                    $StartRow = $dimension.Start.Row
                }
                If(-not $StartColumn)
                {
                    $StartColumn = $dimension.Start.Column
                }
                If(-not $EndRow)
                {
                    $EndRow = $dimension.End.Row
                }
                If(-not $EndColumn)
                {
                    $EndColumn = $dimension.End.Column
                }
            }
            Elseif($PSCmdlet.ParameterSetName -like 'Header')
            {
                $StartRow = $dimension.Start.Row
                $StartColumn = $dimension.Start.Column
                $EndRow = $dimension.Start.Row
                $EndColumn = $dimension.End.Column
            }

            $Start = ConvertTo-ExcelCoordinate -Row $StartRow -Column $StartColumn
            $End = ConvertTo-ExcelCoordinate -Row $EndRow -Column $EndColumn
            $RangeCoordinates = "$Start`:$End"

        # Apply the formatting
            $CellRange = $WorkSheet.Cells[$RangeCoordinates]
            
            switch ($PSBoundParameters.Keys)
            {
                'Bold'                { $CellRange.Style.Font.Bold = $Bold  }
                'Italic'              { $CellRange.Style.Font.Italic = $Italic  }
                'Underline'           { $CellRange.Style.Font.UnderLine = $Underline}
                'Size'                { $CellRange.Style.Font.Size = $Size }
                'Font'                { $CellRange.Style.Font.Name = $Font }
                'Color'               { $CellRange.Style.Font.Color.SetColor($ColorConverted) }
                'BackgroundColor'     {
                    $CellRange.Style.Fill.PatternType = $FillStyle
                    $CellRange.Style.Fill.BackgroundColor.SetColor($BackgroundColorConverted)
                }
                'WrapText'            { $CellRange.Style.WrapText = $WrapText  }
                'VerticalAlignment'   { $CellRange.Style.VerticalAlignment = $VerticalAlignment }
                'HorizontalAlignment' { $CellRange.Style.HorizontalAlignment = $HorizontalAlignment }
                'AutoFilter'          { $CellRange.AutoFilter = $AutoFilter }
                'Autofit'         {
                    #Probably a cleaner way to call this...
                    try
                    {
                        if($PSBoundParameters.ContainsKey('AutofitMaxWidth'))
                        {
                            $CellRange.AutoFitColumns($AutofitMinWidth, $AutofitMaxWidth)
                        }
                        elseif($PSBoundParameters.ContainsKey('AutofitMinWidth'))
                        {
                            $CellRange.AutoFitColumns($AutofitMinWidth)
                        }
                        else
                        {
                            $CellRange.AutoFitColumns()
                        }
                    }
                    Catch
                    {
                        Write-Error $_
                    }
                }
                'Border' {
                    If($Border -eq '*')
                    {
                        $Border = 'Top', 'Bottom', 'Left', 'Right'
                    }
                    foreach($Side in @( $Border | Select -Unique ) )
                    {
                        if(-not $BorderStyle)
                        {
                            $BorderStyle = [OfficeOpenXml.Style.ExcelBorderStyle]::Thin
                        }
                        if(-not $BorderColorConverted)
                        {
                            $BorderColorConverted = [System.Drawing.Color]::Black
                        }
                        $CellRange.Style.Border.$Side.Style = $BorderStyle
                        $CellRange.Style.Border.$Side.Color.SetColor( $BorderColorConverted )
                    }
                }
                'NumberFormat' {
                    $CellRange.Style.Numberformat.Format = $NumberFormat
                }
            }
        if($Passthru)
        {
            $WorkSheet
        }
    }
}