python调用win32接口在excel中作像素画 发表于 2016-04-08 | 分类于 Python | 取一张图片的每个像素点,然后将其插入到单元格中 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960#coding=utf-8from PIL import Imageimport win32com.clientimport sysimport osdef getImageRGBdata(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 whlistdef rgb_to_hex(rgb): bgr=tuple(reversed(rgb)) strValue = '%02x%02x%02x' % bgr iValue = int(strValue, 16) return iValuedef 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:\workspace\pytest\images\xxxxxxxxx.jpg' savename=r'20151218.xlsx' else: imgpath=argv[0] savename=argv[1] main(imgpath,savename)