前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python-Excel-04-单元格上个底色

Python-Excel-04-单元格上个底色

作者头像
zishendianxia
发布2019-10-23 17:13:32
1.1K0
发布2019-10-23 17:13:32
举报
文章被收录于专栏:Python工程师Python工程师

系统:Windows 7

语言版本:Anaconda3-4.3.0.1-Windows-x86_64

编辑器:pycharm-community-2016.3.2

  • 这个系列讲讲PythonExcel的操作
  • 今天讲讲win32com模块对已有Excel文件的操作:单元格增加底色

目录

Part 1:示例说明

  1. 示例工作表第1行数据,如果数据大于5,则单元格底色涂为红色

原数据

程序运行后

目录

Part 2:代码

代码语言:javascript
复制
import os
import win32com
from win32com.client import constants as c  # 旨在直接使用VBA常数

current_address = os.path.abspath('.')excel_address = os.path.join(current_address, "示例.xlsx")
print(current_address)
xl_app = win32com.client.gencache.EnsureDispatch("Excel.Application")  # 若想引用常数的话使用此法调用Excel
xl_app.Visible = False  # 是否显示Excel文件

wb = xl_app.Workbooks.Open(excel_address)
sht = wb.Worksheets(1)
sht.Name = "示例"

max_col = sht.Cells(1, sht.Columns.Count).End(c.xlToLeft).Column

for j in range(1, max_col+1):
   print(j)
   cells_value = sht.Cells(1, j).Value    
    if cells_value > 5:
       sht.Cells(1, j).Interior.Pattern = c.xlSolid
       sht.Cells(1, j).Interior.PatternColorIndex = c.xlAutomatic
       sht.Cells(1, j).Interior.Color = 255
       sht.Cells(1, j).Interior.TintAndShade = 0
       sht.Cells(1, j).Interior.PatternTintAndShade = 0

wb.Save()
wb.Close()

代码截图

目录

Part 3:部分代码解读

  1. max_col = sht.Cells(1, sht.Columns.Count).End(c.xlToLeft).Column获取最大列,用法上与VBA一样,只是在常数前加了一个c
  2. sht.Cells(1, j).Interior.Color = 255,如果需要更换颜色,请在Excel使用录制宏功能,看一下不同颜色数值
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-01-08,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python工程师 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档