回答編集履歴
1
勘違いしていた部分に取り消し線追加など
answer
CHANGED
@@ -1,8 +1,9 @@
|
|
1
|
-
ざっくりとしかコードを見てませんがまず一つ。
|
1
|
+
~~ざっくりとしかコードを見てませんがまず一つ。
|
2
|
-
|
3
2
|
**バイナリファイルはテキストファイルではありません**
|
4
|
-
出力時はちゃんとByteに変換してあげてください。
|
3
|
+
出力時はちゃんとByteに変換してあげてください。~~
|
5
4
|
|
5
|
+
(Byte配列化されているので、バイナリの形式の問題だと思われます)
|
6
|
+
|
6
7
|
また全部手実装するよりは、多少汚くても既存機能を使った方が楽です。
|
7
8
|
|
8
9
|
クリップボードを経由しますが、ExcelのVBAだけで完結する例
|
@@ -36,4 +37,65 @@
|
|
36
37
|
if ([Windows.Forms.Clipboard]::ContainsImage()) {
|
37
38
|
[Windows.Forms.Clipboard]::GetImage().Save('保存先', 'Bmp')
|
38
39
|
}
|
40
|
+
```
|
41
|
+
|
42
|
+
###### 蛇足:Excelの選択範囲を画像化して保存するPowerShellスクリプト
|
43
|
+
|
44
|
+
```
|
45
|
+
# Excelの選択範囲を画像化して保存するスクリプト PowerShell ISE に張り付けて実行
|
46
|
+
$ErrorActionPreference = 'Stop'
|
47
|
+
|
48
|
+
# bmpの保存先
|
49
|
+
[string]$savePath = [IO.Path]::Combine([Environment]::GetFolderPath('MyPictures'), 'pstmp.bmp')
|
50
|
+
# 一セルあたり何ピクセルで表現するか
|
51
|
+
[int]$zoom = 2
|
52
|
+
|
53
|
+
# Excelを取得
|
54
|
+
[__ComObject]$appXl = [Runtime.InteropServices.Marshal]::GetActiveObject('Excel.Application')
|
55
|
+
[__ComObject]$srcRng = $appXl.Selection
|
56
|
+
|
57
|
+
# 範囲の行数取得
|
58
|
+
[int]$rowCnt, [int]$colCnt = $srcRng.Rows.Count, $srcRng.Columns.Count # TODO:COM Release
|
59
|
+
|
60
|
+
# 出力する画像をインスタンス
|
61
|
+
[hashtable]$bmpArg = @{
|
62
|
+
TypeName = 'Drawing.Bitmap'
|
63
|
+
ArgumentList = ($colCnt * $zoom), ($rowCnt * $zoom)
|
64
|
+
}
|
65
|
+
[Drawing.Bitmap]$bmp = New-Object @bmpArg
|
66
|
+
|
67
|
+
# [Excel.Range].Interior.Color => [Drawing.Color]
|
68
|
+
Function XlRGBtoDrawColor([int]$XlRGB) {
|
69
|
+
return [Drawing.Color]::FromArgb( #もっと良い方法がありそう
|
70
|
+
$XlRGB -band 0xFF, # Red
|
71
|
+
($XlRGB -band 0xFF00) / 0x100, # Green
|
72
|
+
($XlRGB -band 0xFF0000) / 0x10000 # Blue
|
73
|
+
)
|
74
|
+
}
|
75
|
+
|
76
|
+
# セル範囲ループ
|
77
|
+
for ($r = 1 ; $r -le $rowCnt ; $r += 1) {
|
78
|
+
for ($c = 1 ; $c -le $colCnt ; $c += 1) {
|
79
|
+
[Drawing.Color]$drwClr = XlRGBtoDrawColor -XlRGB ($srcRng.Item($r , $c).Interior.Color) # TODO:COM Release
|
80
|
+
# セル座標は1始まり、画像内座標は0始まり
|
81
|
+
[int]$startX = ($c - 1) * $zoom
|
82
|
+
[int]$startY = ($r - 1) * $zoom
|
83
|
+
|
84
|
+
# zoom分塗りつぶしのループ もっと良い方法がありそう
|
85
|
+
for($x = $startX ; $x -lt $startX + $zoom ; $x += 1) {
|
86
|
+
for($y = $startY ; $y -lt $startY + $zoom ; $y += 1) {
|
87
|
+
$bmp.SetPixel($x, $y, $drwClr)
|
88
|
+
}
|
89
|
+
}
|
90
|
+
|
91
|
+
}
|
92
|
+
}
|
93
|
+
|
94
|
+
# COM解放(適当)
|
95
|
+
[Runtime.InteropServices.Marshal]::FinalReleaseComObject($srcRng) > $null ; $srcRng = $null
|
96
|
+
[Runtime.InteropServices.Marshal]::FinalReleaseComObject($appXl) > $null ; $appXl = $null
|
97
|
+
|
98
|
+
# 保存
|
99
|
+
$bmp.Save($savePath, 'bmp')
|
100
|
+
explorer "/select,$savePath"
|
39
101
|
```
|