Skip to content

Instantly share code, notes, and snippets.

@xavierskip
Created October 1, 2021 13:56
Show Gist options
  • Save xavierskip/214f110b0a966a14bbc2965362a61890 to your computer and use it in GitHub Desktop.
Save xavierskip/214f110b0a966a14bbc2965362a61890 to your computer and use it in GitHub Desktop.
convert img to excel
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]))
@xavierskip
Copy link
Author

xavierskip commented Oct 1, 2021

目前已知bug,某些图片显示转换完成后,点击打开excel会报错,选择修复会有以下提示,

已删除的部件: 部件 /xl/styles.xml。 (样式)
已修复的记录: /xl/worksheets/sheet1.xml 部分的 单元格信息

出错图片的分辨率为 738x525,有分辨率更大的图片能够正常显示,所以应该不是图片大小的问题,可能是图片颜色的问题。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment