python pywin32 处理Excel如何添加某个单元格背景颜色

如题所述

#Win32#打开EXCEL
WinApp = win32com.client.DispatchEx('Excel.Application')
#要处理的excel文件路径#out.file是文件  绝对路径
WinBook = WinApp.Workbooks.Open(out_file)
 #要处理的excel页
WinSheet = WinBook.Worksheets('Sheet1')

#单元格添加颜色
WinSheet.Cells(1, 1).Interior.ColorIndex = 3
#或者Range("A1") 
WinSheet.Range("A1").Interior.ColorIndex = 3   
#3=红色,不同的值代表不同的颜色,可以去查看msdn  vba 文档,这就不详细说了

#再是RGB调色方式#Cells 和 Range都可以,Range可以选择一大片区域
WinSheet.Cells(1, 1).Interior.Color = RGB(0, 0, 255) 
#或
WinSheet.Range("A1").Interior.Color = RGB(255, 0, 255) 
#字体的颜色也是一样
WinSheet.Cells(1, 1).Font.ColorIndex = 3
WinSheet.Cells(1, 1).Font.Color = RGB(0, 0, 255)

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-06-21

#!/usr/bin/python
from win32com.client import Dispatch
import os

#打开excel app
xlApp = Dispatch('Excel.Application')
xlApp.Visible = True
#要处理的excel文件路径#out.file是文件  绝对路径
workbook = xlApp.Workbooks.Open(os.path.join(os.getcwd(), 'test1.xlsx'))
WinSheet = workbook.Worksheets('Sheet1')

#这是关键!!!!!

def rgb_to_hex(rgb):
bgr = (rgb[2], rgb[1], rgb[0])
strValue = '%02x%02x%02x' % bgr
# print(strValue)
iValue = int(strValue, 16)
return iValue

WinSheet.Cells(1, 1).Interior.Color = rgb_to_hex((255,0,0))

#以后有事问Google,百度真坑爹

相似回答