Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $scriptPath = $MyInvocation.MyCommand.Path
- write-host $scriptPath
- $nofilePath = Split-Path -Parent $scriptPath
- function Export-Excel([Array]$data, [string]$outfilename) {
- function Get-Keys([Array]$data) {
- $keys = New-Object System.Collections.Generic.HashSet[string]
- $data | ForEach-Object {
- $item = $_
- $item | Get-Member -MemberType NoteProperty | select -ExpandProperty Name | ForEach-Object {
- $keys.Add($_) | Out-Null
- }
- }
- return $keys
- }
- $keys = Get-Keys($data)
- try {
- $excel = New-Object -ComObject Excel.Application
- $excel.Visible = $true
- $excel.DisplayAlerts = $true
- $book = $excel.Workbooks.Add()
- $book.Sheets(1).Name = "data"
- $sheet = $book.Sheets("data") # 扱いやすいようにシートを取得します
- $sheet.Name # hoge と出るはずです
- $keys | ForEach-Object { $j = 1 } {
- $sheet.Cells.Item(1, $j) = $_
- $j++
- }
- $data | ForEach-Object { $i = 2 } {
- $item = $_
- $keys | ForEach-Object { $j = 1 } {
- $key = $_
- $sheet.Cells.Item($i, $j) = $item.$key
- $j++
- }
- $i++
- }
- $book.SaveAs($nofilePath + "\" + $outfilename)
- $excel.Quit() # Excel の終了
- }
- finally {
- [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null # 変数の破棄
- [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet) | Out-Null # 変数の破棄
- # null破棄
- $excel, $book, $sheet | foreach {$_ = $null}
- }
- }
- $data = @()
- $data += [PSCustomObject]@{
- Name = "unko"
- Name2 = "unkounko"
- Name3 = "unkounkounko"
- }
- $data += [PSCustomObject]@{
- Name = "unko2"
- Name2 = "unkounko2"
- }
- Export-Excel $data "a.xlsx"
Add Comment
Please, Sign In to add comment