python-自动篇-办公-用Excel画画

本文介绍了作者在使用Python代码将图片转换为Excel中的颜色样式时遇到的两个问题:ModuleNotFoundError(缺少xlsxwriter模块)和FileNotFoundError(找不到指定的图片文件)。解决方案包括安装xlsxwriter模块和确保图片文件位于正确路径。
摘要由CSDN通过智能技术生成

代码

# coding: utf-8

from PIL import Image
from xlsxwriter.workbook import Workbook


class ExcelPicture(object):
    FORMAT_CONSTRAINT = 65536

    def __init__(self, pic_file, ratio=0.5):
        self.__pic_file = pic_file

        self.__ratio = ratio
        self.__zoomed_out = False

        self.__formats = dict()

    # 缩小图片
    def zoom_out(self, _img):
        _size = _img.size
        _img.thumbnail((int(_img.size[0] * self.__ratio), int(_img.size[1] * self.__ratio)))

        self.__zoomed_out = True

    # 对颜色进行圆整
    def round_rgb(self, rgb, model):
        return tuple([int(round(x / model) * model) for x in rgb])

    # 查找颜色样式,去重
    def get_format(self, color):
        _format = self.__formats.get(color, None)

        if _format is None:
            _format = self.__wb.add_format({'bg_color': color})
            self.__formats[color] = _format

        return _format

    # 操作流程
    def process(self, output_file='_pic.xlsx', color_rounding=False, color_rounding_model=5.0):
        # 创建xlsx文件,并调整行列属性
        self.__wb = Workbook(output_file)
        self.__sht = self.__wb.add_worksheet()
        self.__sht.set_default_row(height=9)
        self.__sht.set_column(0, 5000, width=1)

        # 打开需要进行转换的图片
        _img = Image.open(self.__pic_file)
        print        ('Picture filename:', self.__pic_file)

        # 判断是否需要缩小图片尺寸
        if self.__ratio < 1:
            self.zoom_out(_img)

        # 遍历每一个像素点,并填充对应的颜色到对应的Excel单元格
        _size = _img.size
        print('Picture size:', _size)
        for (x, y) in [(x, y) for x in range(_size[0]) for y in range(_size[1])]:
            _clr = _img.getpixel((x, y))

            # 如果颜色种类过多,则需要将颜色圆整到近似的颜色上,以减少颜色种类
            if color_rounding: _clr = self.round_rgb(_clr, color_rounding_model)

            _color = '#%02X%02X%02X' % _clr
            self.__sht.write(y, x, '', self.get_format(_color))

        self.__wb.close()

        # 检查颜色样式种类是否超出限制,Excel2007对样式数量有最大限制
        format_size = len(self.__formats.keys())
        if format_size >= ExcelPicture.FORMAT_CONSTRAINT:
            print('Failed! Color size overflow: %s.' % format_size)
        else:
            print            ('Success!')
            print            ('Color: %s' % format_size)
            print            ('Color_rounding:', color_rounding)
            if color_rounding:
                print            ('Color_rounding_model:', color_rounding_model)


if __name__ == '__main__':
    r = ExcelPicture('111.jpg', ratio=0.5)
    r.process('0407.xlsx', color_rounding=True, color_rounding_model=5.0)

所遇问题

ModuleNotFoundError: No module named ‘xlsxwriter’

在这里插入图片描述
如果错误仍然存​​在,请获取您的 Python 版本并确保您使用正确的 Python 版本安装包。

pip3.11 install xlsxwriter

在这里插入图片描述

FileNotFoundError: [Errno 2] No such file or directory: ‘111.jpg’

在这里插入图片描述
需要将图片111和excel放到根目录下
在这里插入图片描述

效果

在这里插入图片描述
在这里插入图片描述

附件

图片

图片改名为111
在这里插入图片描述
在这里插入图片描述

excel

excel改名为0427
在这里插入图片描述

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fo安方

觉得俺的文章还行,感谢打赏,爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值