python调用win32接口在excel中作像素画

取一张图片的每个像素点,然后将其插入到单元格中

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
from PIL import Image
import win32com.client
import sys
import os
def (imgpath):
img=Image.open(imgpath)
width,height=img.size
data=img.getdata()
datalist=list(data)
whlist=[]
j=0
for i in range(height):
whlist.append(datalist[j:(i+1)*width])
j=(i+1)*width
return whlist
def rgb_to_hex(rgb):
bgr=tuple(reversed(rgb))
strValue = '%02x%02x%02x' % bgr
iValue = int(strValue, 16)
return iValue
def creatExcel(imgdata,savename):
xl = win32com.client.Dispatch("Excel.Application")
ss = xl.Workbooks.Add()
sh = ss.ActiveSheet
xl.Visible = True
for i,line in enumerate(imgdata):
print "draw %d line" % i
for j,col in enumerate(imgdata[i]):
sh.Cells(i+1,j+1).Interior.Color=rgb_to_hex(col)
sh.Cells(i+1,j+1).RowHeight=3
sh.Cells(i+1,j+1).ColumnWidth=0.3
curdir=os.getcwd()
ss.SaveAs(curdir+"\"+savename)
ss.Close(False)
xl.Application.Quit()
def main(imgpath,savename):
imgdata=getImageRGBdata(imgpath)
creatExcel(imgdata,savename)
if __name__=="__main__":
argv=sys.argv[1:]
if not argv:
imgpath=r'E:workspacepytestimagesxxxxxxxxx.jpg'
savename=r'20151218.xlsx'
else:
imgpath=argv[0]
savename=argv[1]
main(imgpath,savename)