Created
October 1, 2021 13:56
-
-
Save xavierskip/214f110b0a966a14bbc2965362a61890 to your computer and use it in GitHub Desktop.
convert img to excel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from openpyxl import Workbook | |
from openpyxl.styles import PatternFill | |
from PIL import Image | |
import sys | |
''' | |
require: python3 pillow openpyxl | |
usage: python3 img2excel 1.jpg out | |
''' | |
imgfile = sys.argv[1] | |
im = Image.open(imgfile) | |
print(im.format, im.size, im.mode) | |
width,height = im.size | |
px = im.load() | |
wb = Workbook() | |
ws = wb.active | |
ws.sheet_format.defaultColWidth = 2.0 | |
ws.sheet_format.defaultRowHeight = 2.0 * (2.2863/0.3612) | |
for h in range(height): | |
for w in range(width): | |
c = ws.cell(row=h+1, column=w+1) | |
r, g, b = px[w, h][0:3] | |
color = "{:02x}{:02x}{:02x}".format(r, g, b) | |
c.fill = PatternFill("solid", fgColor=color) | |
wb.save('{}.xlsx'.format(sys.argv[2])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
目前已知bug,某些图片显示转换完成后,点击打开excel会报错,选择修复会有以下提示,
出错图片的分辨率为 738x525,有分辨率更大的图片能够正常显示,所以应该不是图片大小的问题,可能是图片颜色的问题。