Guest User

Untitled

a guest
Jun 19th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. $scriptPath = $MyInvocation.MyCommand.Path
  2. write-host $scriptPath
  3. $nofilePath = Split-Path -Parent $scriptPath
  4.  
  5. function Export-Excel([Array]$data, [string]$outfilename) {
  6. function Get-Keys([Array]$data) {
  7. $keys = New-Object System.Collections.Generic.HashSet[string]
  8. $data | ForEach-Object {
  9. $item = $_
  10. $item | Get-Member -MemberType NoteProperty | select -ExpandProperty Name | ForEach-Object {
  11. $keys.Add($_) | Out-Null
  12. }
  13. }
  14. return $keys
  15. }
  16.  
  17. $keys = Get-Keys($data)
  18. try {
  19. $excel = New-Object -ComObject Excel.Application
  20. $excel.Visible = $true
  21. $excel.DisplayAlerts = $true
  22. $book = $excel.Workbooks.Add()
  23. $book.Sheets(1).Name = "data"
  24. $sheet = $book.Sheets("data") # 扱いやすいようにシートを取得します
  25. $sheet.Name # hoge と出るはずです
  26. $keys | ForEach-Object { $j = 1 } {
  27. $sheet.Cells.Item(1, $j) = $_
  28. $j++
  29. }
  30. $data | ForEach-Object { $i = 2 } {
  31. $item = $_
  32. $keys | ForEach-Object { $j = 1 } {
  33. $key = $_
  34. $sheet.Cells.Item($i, $j) = $item.$key
  35. $j++
  36. }
  37. $i++
  38. }
  39.  
  40. $book.SaveAs($nofilePath + "\" + $outfilename)
  41. $excel.Quit() # Excel の終了
  42. }
  43. finally {
  44. [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null # 変数の破棄
  45. [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet) | Out-Null # 変数の破棄
  46. # null破棄
  47. $excel, $book, $sheet | foreach {$_ = $null}
  48. }
  49. }
  50.  
  51.  
  52. $data = @()
  53. $data += [PSCustomObject]@{
  54. Name = "unko"
  55. Name2 = "unkounko"
  56. Name3 = "unkounkounko"
  57. }
  58. $data += [PSCustomObject]@{
  59. Name = "unko2"
  60. Name2 = "unkounko2"
  61. }
  62.  
  63. Export-Excel $data "a.xlsx"
Add Comment
Please, Sign In to add comment