Set-CellValue.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
function Set-CellValue {
    <#
    .SYNOPSIS
        Set the value of a specific cell or range
 
    .DESCRIPTION
        Set the value of a specific cell or range
 
        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 CellRange
        CellRange to set value on. This is an ExcelRangeBase
 
        See help for Search-CellValue, with the '-As Passthru' parameter. This generates an ExcelRangeBase
 
    .PARAMETER Excel
        An Excel object to set values in. We do not save this.
 
    .PARAMETER Path
        A path to set values in. We save changes to this.
 
    .PARAMETER Worksheet
        A worksheet to set values in.
     
    .PARAMETER WorksheetName
        A specific worksheet to set values in, otherwise, assume all worksheets from the input object
 
    .PARAMETER Coordinates
        Excel style coordinates specifying starting cell and final cell (e.g. A1:B2)
 
        If not specified, we get the dimension for the worksheet and change everything.
 
    .PARAMETER Value
        The value to set cells to.
 
    .PARAMETER Passthru
        If specified, passthru the inputobject (Excel, Worksheet, or Cellrange)
 
    .EXAMPLE
        Set-CellValue -Path C:\Temp\Demo.xlsx -Coordinates a1:a1 -Value Header1
 
        #Set the first column header to 'Header1'
 
    .EXAMPLE
         
        #
        # Open an existing XLSX to search and set cells within
        $Excel = New-Excel -Path C:\Temp\Demo.xlsx
 
        #Search for any cells like 'jsmith*'. Set them all to REDACTED
        $Excel | Search-CellValue {$_ -like 'jsmith*'} -As Passthru | Set-CellValue -Value "REDACTED"
 
        #Save your changes and close the ExcelPackage
        $Excel | Save-Excel -Close
 
    .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
    #>

    [cmdletbinding(DefaultParametersetName = 'CellRange')]
    param(
        [parameter( Position = 0,
                    ParameterSetName = 'CellRange',
                    Mandatory=$true,
                    ValueFromPipeline=$true,
                    ValueFromPipelineByPropertyName=$true)]
        [OfficeOpenXml.ExcelRangeBase]$CellRange,

        [parameter( Position = 0,
                    ParameterSetName = 'Excel',
                    Mandatory=$true,
                    ValueFromPipeline=$true,
                    ValueFromPipelineByPropertyName=$true)]
        [OfficeOpenXml.ExcelPackage]$Excel,

        [parameter( Position = 0,
                    ParameterSetName = 'File',
                    Mandatory=$true,
                    ValueFromPipeline=$true,
                    ValueFromPipelineByPropertyName=$true)]
        [validatescript({Test-Path $_})]
        [string]$Path,

        [parameter( Position = 0,
                    ParameterSetName = 'Worksheet',
                    Mandatory=$true,
                    ValueFromPipeline=$true,
                    ValueFromPipelineByPropertyName=$true)]
        [OfficeOpenXml.ExcelWorksheet]$WorkSheet,

        [parameter(ParametersetName = 'Excel')]
        [parameter(ParametersetName = 'File')]
        [parameter(ParametersetName = 'Worksheet')]        
        [string]$WorksheetName,

        [parameter(ParametersetName = 'Excel')]
        [parameter(ParametersetName = 'File')]
        [parameter(ParametersetName = 'Worksheet')]
        [validatescript({
            if( $_ -match "^[a-zA-Z]+[0-9]+:[a-zA-Z]+[0-9]+$" )
            {
                $True
            }
            else
            {
                Throw "'$_' is not a valid coordinate. See help for 'Coordinates' parameter"
            }
        
        })]
        [string]$Coordinates,

        $Value,

        [parameter(ParametersetName = 'Excel')]
        [parameter(ParametersetName = 'CellRange')]
        [parameter(ParametersetName = 'Worksheet')]
        [switch]$Passthru

    )
    Process
    {
        Write-Verbose "PSBoundParameters: $($PSBoundParameters | Out-String)"    

        $WSParam = @{}
        if($PSBoundParameters.ContainsKey( 'WorkSheetName') )
        {
            $WSParam.Add('Name',$WorkSheetName)
        }
        Try
        {
            switch ($PSCmdlet.ParameterSetName)
            {
                'Excel'
                {
                    $WorkSheets = @( $Excel | Get-Worksheet @WSParam -ErrorAction Stop )
                }
                'File'
                {
                    $Excel = New-Excel -Path $Path -ErrorAction Stop
                    $WorkSheets = @( $Excel | Get-Worksheet @WSParam -ErrorAction Stop )
                }
                'Worksheet'
                {
                    $WorkSheets = @( $WorkSheet )
                }
                'CellRange'
                {
                    $WorkSheets = @( $CellRange.Worksheet | Select -First 1 )
                }
            }
        }
        Catch
        {
            Throw "Could not get worksheets to search: $_"
        }

        If($WorkSheets.Count -eq 0)
        {
            Throw "Something went wrong, we didn't find a worksheet"
        }


        foreach($Worksheet in $Worksheets)
        {
            if($PSCmdlet.ParameterSetName -notlike 'CellRange')
            {
                Write-Verbose "Working with worksheet $($Worksheet.Name)"
                if($PSBoundParameters.ContainsKey('Coordinates'))
                {
                    Try
                    {
                        $CellRange = $WorkSheet.Cells.item($Coordinates)
                    }
                    Catch
                    {
                        Write-Error "Could not get cells from '$($WorkSheet.Name)' for coordinates '$Coordinates'"
                        Continue
                    }
                }
                else
                {
                    $CellRange = $Worksheet.Cells
                }
            }

            $CellRange.Value = $Value
            $StyleName = $null
            $StyleFormat = $null
            Try
            {
                #Nulls will error, catch them
                $ThisType = $Null
                $ThisType = $Value.GetType().FullName
            }
            Catch
            {
                Write-Verbose "Applying no style to null in range $($CellRange.FullAddress)"
            }

            Switch -regex ($ThisType)
            {
                "double|decimal|single"
                {
                    $StyleFormat = "0.00"
                }
                "int\d\d$"
                {
                    $StyleFormat = "0"
                }
                "datetime"
                {
                    $StyleFormat = "M/d/yyy h:mm"
                }
                default
                {
                    #No default yet...
                }
            }

            if($StyleFormat)
            {
                $CellRange.Style.Numberformat.Format = $StyleFormat
            }
        }

        switch($PSCmdlet.ParameterSetName)
        {
            'File'
            {
                $Excel.save()
            }
            'Excel'
            {
                if($Passthru) {$Excel}
            }
            'Worksheet'
            {
                if($Passthru) {$Worksheet}
            }
            'CellRange'
            {
                if($Passthru) {$CellRange}
            }
        }
    }
}