查看原文
其他

Python小玩意 | 操作excel来作画

小小明 可以叫我才哥 2021-10-08


作者:小小明

Pandas数据处理专家,致力于帮助无数数据从业者解决数据处理难题。

大家好,今天我们带来小小明的一个小玩意,用excel作画。原理上就是:读取原图每个像素的颜色值,然后再填充到excel对应单元格

  • 读取原图每个像素颜色值 用到 PIL 库
  • 填充excel单元格颜色呢 用到 openpyxl 库

比如我们有这样一张图片:

原图

想把它画到excel上:

效果

该如何实现呢?

python几分钟内轻松实现!看看代码吧:

from openpyxl.utils import get_column_letter
from openpyxl.styles import PatternFill
from openpyxl import Workbook
from PIL import Image

im = Image.open("logo2.jpg")
im = im.resize((8080))
data = im.load()

book = Workbook()
sheet = book.active
for row in range(1, im.height+1):
    for col in range(1, im.width+1):
        p = data[col-1, row-1]
        color = f"{p[0]:0>2x}{p[1]:0>2x}{p[2]:0>2x}"
        sheet.cell(row, col).fill = PatternFill(
            fill_type="solid", fgColor=color)
    sheet.row_dimensions[row].height = 3
for col in range(1, im.width+1):
    sheet.column_dimensions[get_column_letter(col)].width = 0.5

book.save("t.xlsx")

上面代码即可将图片logo2.jpg转为t.xlsx的字符图。

如果你缺少部分库,无法运行,可以使用pip安装:

pip install pillow
pip install openpyxl
- END -


: . Video Mini Program Like ,轻点两下取消赞 Wow ,轻点两下取消在看

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存