python实现xlwt xlrd 指定条件给excel行添加颜色

先用xlrd读excel文件--》book对象a

拿到指定的sheet页 xlrd对象

用xlutils copy 的copy方法复制 a得到b

通过判断a的列值,来修改b

保存b 得到结果

代码如下:

import xlwt
import xlrd
from xlutils.copy import copy
#创建execl
def create_execl(file_name):
 wb = xlwt.Workbook()
 ws = wb.add_sheet('Info')
 ws.write(0, 0, "1")
 ws.write(1, 0, "2")
 ws.write(2, 0, "3")
 ws.write(3, 0, "2")
 wb.save(file_name)
#单元格上色
def color_execl(file_name):
 styleBlueBkg = xlwt.easyxf('pattern: pattern solid, fore_colour red;') # 红色
 rb = xlrd.open_workbook(file_name)  #打开t.xls文件
 ro = rb.sheets()[0]      #读取表单0
 wb = copy(rb)       #利用xlutils.copy下的copy函数复制
 ws = wb.get_sheet(0)     #获取表单0
 col = 0         #指定修改的列
 for i in range(ro.nrows):    #循环所有的行
  result = int(ro.cell(i, col).value)
  if result == 2:      #判断是否等于2
   ws.write(i,col,ro.cell(i, col).value,styleBlueBkg)
 wb.save(file_name)
 
if __name__ == '__main__':
 file_name = 't.xls'
 create_execl(file_name)
 color_execl(file_name)

以上这篇python实现xlwt xlrd 指定条件给excel行添加颜色就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持来客网。