【转载】Python-如何对excel中某一列某些值的单元格着色
效果:
代码如下:
1 import xlwt 2 import xlrd 3 from xlutils.copy import copy 4 #创建execl 5 def create_execl(file_name): 6 wb = xlwt.Workbook() 7 ws = wb.add_sheet('Info') 8 ws.write(0, 0, "1") 9 ws.write(1, 0, "2") 10 ws.write(2, 0, "3") 11 ws.write(3, 0, "2") 12 wb.save(file_name) 13 #单元格上色 14 def color_execl(file_name): 15 styleBlueBkg = xlwt.easyxf('pattern: pattern solid, fore_colour red;') # 红色 16 rb = xlrd.open_workbook(file_name) #打开t.xls文件 17 ro = rb.sheets()[0] #读取表单0 18 wb = copy(rb) #利用xlutils.copy下的copy函数复制 19 ws = wb.get_sheet(0) #获取表单0 20 col = 0 #指定修改的列 21 for i in range(ro.nrows): #循环所有的行 22 result = int(ro.cell(i, col).value) 23 if result == 2: #判断是否等于2 24 ws.write(i,col,ro.cell(i, col).value,styleBlueBkg) 25 wb.save(file_name) 26 27 if __name__ == '__main__': 28 file_name = 't.xls' 29 create_execl(file_name) 30 color_execl(file_name)
感谢作者的知识分享,本文转自:https://blog.csdn.net/hujinhong145/article/details/104397554?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-3&spm=1001.2101.3001.4242