Python3,19行代码,我把她的照片写入到Excel中,2022年伊始,她终于被我感动了。

简介: Python3,19行代码,我把她的照片写入到Excel中,2022年伊始,她终于被我感动了。

1、引言

小屌丝:鱼哥,新年快乐~ ~

小鱼:新年快乐,小屌丝,虽然是元旦,但是也算是迈入新的一年了,也该有新的形象了。

小屌丝:鱼哥,你说的没错啊,新的一年,我要用新的姿势去追妹子。

小鱼:… 怎么三句不说妹子,你无话可说了??

小屌丝:妹子是我提升技术的动力!

小鱼:… 好吧,只要你能提升技能,其他的都无所谓…

小屌丝:呦吼~~ 对了鱼哥,我记得你有一篇博文,把文字写在图片里。

小鱼:对哦,不少小伙伴通过这个方式,让自己的女友感动了。

小屌丝:那能不能把图片写在别的地方呢?

小鱼:例如呢??

小屌丝:excel,word,PDF 等等…

小鱼:…唉我去~~

小屌丝:嘿嘿~ ~ 来嘛 ~ ~

2、代码实战

2.1 思路

我们今天要分享的,是把图片写入到excel中,

注意:

这里说的,不是截取一张图片,粘贴到excel;
而是通过像素写入到excel中。

我们来捋一下思路:

  • 准备源图片,目标excel;
  • 通过Pillow 来读图片的取像素(RGB);
  • 通过openpyxl 向excel cell内填充十六进制色值;
  • 最后把转换的RGB像素直接写入到excel中;

说到这里,就们就来分步实现。

2.2 文件准备

需要写入而Excel的源图片:

2.3 实战

2.3.1 安装

本次需要用到两个模块: Pillow 和 openpyxl

老规矩, pip 方式安装:

pip install Pillow 
pip install openpyxl

其他方式安装:

Python3,选择Python自动安装第三方库,从此跟pip说拜拜!!

Python3:我低调的只用一行代码,就导入Python所有库!!

2.3.2 代码实战

1、色值转换

由于 图片读取的像素是RGB值,而excel是十六进制写入,

所以需要定义一个RGB与十六进制转换的函数

# -*- coding:utf-8 -*-
# @Time   : 2022-01-03
# @Author : carl_DJ
'''
定义RGB 和十六进制色值转换函数
'''
def rgb_to_hex(rgb):
    rgb = rgb.split(',')
    color = ''
    #循环遍历
    for i in rgb:
        num = int(i)
        color  += str(hex(num))[-2:].replace('x','0').upper()
    return  color

2、图片转换

此操作是逐行读取图片的 RGB 色值,再将 RGB 色值转换为十六进制色值填充到 Excel 的 cell 中。

# -*- coding:utf-8 -*-
# @Time   : 2022-01-03
# @Author : carl_DJ
'''
逐行读取图片中的RGB色值,再将RGB色值转换十六进制,填充到excel中
'''
def img_to_excel(img_path,excel_path):
    #读取源图片
    img_src = Image.open(img_path)
    #设置图片宽高
    img_width = img_src.size[0]
    img_hight = img_src.size[1]
    #图片加载
    str_strlist = img_src.load()
    #获取当前的excel文件
    wb = openpyxl.Workbook()
    #保存文件
    wb.save(excel_path)
    #打开excel_path 下的excel文件,并写入信息
    wb = openpyxl.load_workbook(excel_path)
    cell_width,cell_height = 1.0,1.0
    #设置excel的写入页
    sheet = wb['Sheet']
    #循环图片的高与宽,并存入
    for w in range(img_width):
        for h in range(img_hight):
            data = str_strlist[w,h]
            color = str(data).replace("(","").replace(")","")
            color  = rgb_to_hex(color)
            #设置填充颜色为color
            fille = PatternFill("solid",fgColor = color)
            sheet.cell(h + 1,w + 1).fill = fille
    #循环遍历row,让其全部写入
    for i in range(1,sheet.max_row + 1):
        sheet.row_dimensions[i].height = cell_height
    #循环遍历column,让其全部写入
    for i in range(1,sheet.max_column + 1):
        sheet.column_dimensions[get_column_letter(i)].width = cell_width
    #保存文件
    wb.save(excel_path)
    #关闭
    img_src.close()

3、代码整合

# -*- coding:utf-8 -*-
# @Time   : 2022-01-03
# @Author : carl_DJ
import  openpyxl
from openpyxl.styles import PatternFill
from openpyxl.utils import  get_column_letter
from PIL import Image,ImageFont,ImageDraw,ImageColor
'''
色值转换:
从图片读取的像素块色值是 RGB 值,
RGB 和十六进制色值转换。
'''
def rgb_to_hex(rgb):
    rgb = rgb.split(',')
    color = ''
    #循环遍历
    for i in rgb:
        num = int(i)
        color  += str(hex(num))[-2:].replace('x','0').upper()
    return  color
'''
图片转换:
逐行读取图片中的RGB色值,再将RGB色值转换十六进制,填充到excel中
'''
def img_to_excel(img_path,excel_path):
    #读取源图片
    img_src = Image.open(img_path)
    #设置图片宽高
    img_width = img_src.size[0]
    img_hight = img_src.size[1]
    #图片加载
    str_strlist = img_src.load()
    #获取当前的excel文件
    wb = openpyxl.Workbook()
    #保存文件
    wb.save(excel_path)
    #打开excel_path 下的excel文件,并写入信息
    wb = openpyxl.load_workbook(excel_path)
    cell_width,cell_height = 1.0,1.0
    #设置excel的写入页
    sheet = wb['Sheet']
    #循环图片的高与宽,并存入
    for w in range(img_width):
        for h in range(img_hight):
            data = str_strlist[w,h]
            color = str(data).replace("(","").replace(")","")
            color  = rgb_to_hex(color)
            #设置填充颜色为color
            fille = PatternFill("solid",fgColor = color)
            sheet.cell(h + 1,w + 1).fill = fille
    #循环遍历row,让其全部写入
    for i in range(1,sheet.max_row + 1):
        sheet.row_dimensions[i].height = cell_height
    #循环遍历column,让其全部写入
    for i in range(1,sheet.max_column + 1):
        sheet.column_dimensions[get_column_letter(i)].width = cell_width
    #保存文件
    wb.save(excel_path)
    #关闭
    img_src.close()
if __name__ == '__main__':
    #源图片地址
    img_path = './queue.jgp'
    #保存excel地址
    excel_path = './queue.xlsx'
    #执行
    img_to_excel(img_path, excel_path)

4、运行结果

3、总结

写到这里,今天的分享就就差不多结束了。

因为今天也用到了Pillow,如果想快速入手,可以参照小鱼的这篇博文《Python3,10行代码,我把情书写在她的照片里,她被我的才华征服了。

这里小鱼提醒一下,

如果你的源图片很大,运行完成后,打开Excel会提文件损坏,
因为Excel的行数有限,导致无法全部写完数据。

Excel报错详情:

xml报错详情:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>error254800_05.xml</logFileName><summary>在文件“D:\Project\img\king.xlsx”中检测到错误</summary><removedParts><removedPart>已删除的部件: 部件 /xl/styles.xml。 (样式)</removedPart></removedParts><repairedRecords><repairedRecord>已修复的记录: /xl/worksheets/sheet1.xml 部分的 单元格信息</repairedRecord></repairedRecords></recoveryLog>
目录
相关文章
|
16天前
|
XML 物联网 API
服务端和客户端 RESTful 接口上传 Excel 的 Python 代码
本文作者木头左是物联网工程师,分享如何使用 Python 和 Flask-RESTful 构建一个简单的 RESTful API,实现文件上传功能,特别支持Excel文件。通过安装Flask和Flask-RESTful库,创建Flask应用,实现文件上传接口,并将其添加到API。该方法具有简单易用、灵活、可扩展及社区支持等优点。
服务端和客户端 RESTful 接口上传 Excel 的 Python 代码
|
29天前
|
SQL 人工智能 自然语言处理
Python 潮流周刊#52:Python 处理 Excel 的资源
探索Python精彩:文章涵盖正则、代码恢复、PEP新规范、轻量级打包、在线开发、动态生成GitHub README、自定义linting、代码转图片等。项目资源包括Excel处理、虚拟环境管理、Tensor谜题、依赖注入框架、Web应用转换、AI自动化测试、语法高亮、BI模型查询及Python监控库。在当前环境下,持续学习提升竞争力,Python Weekly提供丰富的学习资源,助力技术精进和职业发展。
|
1月前
|
Python
办公自动化-Python如何提取Word标题并保存到Excel中?
办公自动化-Python如何提取Word标题并保存到Excel中?
52 2
|
1月前
|
Python
python_读写excel、csv记录
python_读写excel、csv记录
27 0
|
14天前
|
测试技术 iOS开发 MacOS
用Python处理Excel的资源
用Python处理Excel的资源
用Python处理Excel的资源
|
5天前
|
存储 数据挖掘 Python
使用Python集合高效统计Excel数据
使用Python集合高效统计Excel数据
18 7
|
10天前
|
API Python
Python库`openpyxl`是一个用于读取和写入Excel 2010 xlsx/xlsm/xltx/xltm文件的库。
【6月更文挑战第19天】`openpyxl`是Python处理xlsx文件的库,支持读写Excel 2010格式。使用`pip install openpyxl`安装。基本操作包括加载文件、读写单元格、操作行和列。例如,加载Excel后,可以读取单元格`A1`的值,或将“Hello, World!”写入`A1`。还可修改单元格内容,如加1后保存到新文件。更多功能,如样式和公式,见官方文档[1]。 [1]: &lt;https://openpyxl.readthedocs.io/en/stable/&gt;
31 1
|
11天前
|
Python
【干货】python xlwt写入excel操作
【干货】python xlwt写入excel操作
12 2
|
10天前
|
Python
【代码】Python实现Excel数据合并
【代码】Python实现Excel数据合并
14 0
|
1月前
|
数据采集 数据挖掘 数据处理
Python数据分析实战:使用Pandas处理Excel文件
Python数据分析实战:使用Pandas处理Excel文件
106 0