Python操作excel-读取、表格填充颜色区分

img

1.场景分析

遇到一个需要读取本地excel数据,处理后打入到数据库的场景,使用java比较重,python很好的解决了这类问题

2.重难点

本场景遇到的重难点在于:

  1. 需要根据表格内的背景颜色对数据进行筛选
  1. 读取非默认Sheet
  1. 总是出现Values must be of type <class ‘str’>问题,后来分析改用cell_fill.start_color.type来判断即可

3.问题解决

from openpyxl import load_workbook
filename = "metadata_comment_dir"  # 读取excel
table="tablename"
workbook = load_workbook(filename)
worksheet = workbook.get_sheet_by_name("SheetName")  # 读取Sheet
#总共有多少行
rows = worksheet.max_row
#总共多少行、多少列并分别赋值
# rows, cols = worksheet.max_row, worksheet.max_column
field_comment = {}
flag =0
for i in range(1, rows+1):
    flag=1
    ce1 = worksheet.cell(row=i, column=1)
    field_comment[table]=worksheet.cell(row=i, column=2).value
    # print(ce1.value)
    if flag==0:
        for j in range(i+2, rows):
            ce2 = worksheet.cell(row=j, column=1)
            if ce2.value != None:
                ce3 = worksheet.cell(row=j, column=3)
                cell_fill=ce2.fill
                # print(ce1.fill.start_color)
                # 值为:rgb=None, indexed=None, auto=None, theme=8, tint=0.8, type='theme'
                if "theme" == cell_fill.start_color.type:
                    # 颜色使用背景颜色
                    cell_color = cell_fill.start_color.theme
                elif "auto" == cell_fill.start_color.type:
                    # 颜色使用自动颜色
                    cell_color = 'Automatic'
                elif "indexed" == cell_fill.start_color.type:
                    # 颜色使用索引颜色
                    cell_color = cell_fill.start_color.indexed
                else  :
                    # 颜色使用rgb颜色
                    cell_color = cell_fill.start_color.rgb
                    field_comment[ce2.value]=ce3.value
                print(field_comment)
            else:
                print(field_comment)
                break
    elif flag==1:
        print(field_comment)
        break
  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值