利用 pywin32 操作 excel

 1 from win32com.client import Dispatch
 2 import win32com.client
 3 import time
 4 
 5 # 获取excel 对象
 6 
 7 excel = win32com.client.Dispatch('Excel.Application')
 8 
 9 """
10 0代表隐藏对象,但可以通过菜单再显示
11 -1代表显示对象
12 2代表隐藏对象,但不可以通过菜单显示,只能通过VBA修改为显示状态
13 """
14 excel.Visible = -1
15 
16 # 打开excel
17 
18 myBook = excel.Workbooks.Open("e:/接口测试用例.xlsx")
19 
20 # sheet页,可以是序号,也可以是名称
21 mySheet = myBook.Worksheets("过程结果")
22 #excel的下标都是从1开始的
23 #mySheet = myBook.Worksheets(1)
24 
25 time.sleep(2)
26 
27 # 删除行,清除历史数据
28 mySheet.Rows("2:500").delete
29 #mySheet.Columns("1").delete
30 
31 # 获取当前sheet页有效的行数
32 LastRow = mySheet.usedrange.rows.count
33 print("该sheet页目前已经存在", LastRow, "")
34 
35 # 获取当前sheet页有效的列数
36 LastColumn = mySheet.usedrange.columns.count
37 print(LastColumn)
38 
39 # 焦点转移到sheet页
40 mySheet.Activate
41 # 给单元格赋值 Cells(行,列)
42 mySheet.Cells(2, 2).Value = "使用win32com"
43 # 设置单元格字体位红色
44 mySheet.Cells(2, 2).Font.Color = -16776961
45 # 设置单元格字体为粗体
46 mySheet.Cells(2, 2).Font.Bold = True
47 # 设置单元格字体
48 mySheet.Cells(2, 2).Font.Name = "微软雅黑"
49 
50 time.sleep(1)
51 
52 mySheet.Activate
53 mySheet.Cells(2, 3).Value = "使用win32com"
54 # 设置单元格字体位绿色
55 mySheet.Cells(2, 3).Font.Color = -11489280
56 mySheet.Cells(2, 3).Font.Bold = True
57 
58 # 获取一个单元格的值
59 aCellValue=mySheet.Cells(2, 3).Value
60 print(aCellValue)
61 
62 
63 # 获取一个范围的值,类型为嵌套的list
64 range_list=mySheet.Range(mySheet.Cells(1, 1), mySheet.Cells(5, 5)).Value
65 
66 # 给一个范围赋值,输入的值应该为嵌套的list
67 mySheet.Range(mySheet.Cells(6, 1), mySheet.Cells(10, 10)).Value = range_list
68 # 改变一个范围的属性值
69 mySheet.Range(mySheet.Cells(6, 1), mySheet.Cells(10, 10)).Font.Color = -11489280
70 
71 # 如果范围是一行的话,赋值应该使用非嵌套的list,例如:
72 row_v=(1,2,3,4)
73 mySheet.Range(mySheet.Cells(11, 1), mySheet.Cells(11, 4)).Value = row_v
74 
75 # 给整个一行赋值,慎用。。。
76 mySheet.Rows(12).Value = row_v
77 print(range_list)
78 
79 #单元格添加颜色
80 WinSheet.Cells(1, 1).Interior.ColorIndex = 3
81 #或者Range("A1") 
82 WinSheet.Range("A1").Interior.ColorIndex = 3   
83 #3=红色,不同的值代表不同的颜色,可以去查看msdn  vba 文档,这就不详细说了
84  
85 #再是RGB调色方式#Cells 和 Range都可以,Range可以选择一大片区域
86 WinSheet.Cells(1, 1).Interior.Color = RGB(0, 0, 255) 
87 #
88 WinSheet.Range("A1").Interior.Color = RGB(255, 0, 255) 
89 #字体的颜色也是一样
90 WinSheet.Cells(1, 1).Font.ColorIndex = 3
91 WinSheet.Cells(1, 1).Font.Color = RGB(0, 0, 255)
92 
93 # 保存
94 myBook.save
95 
96 # 退出
97 myBook.close
原文地址:https://www.cnblogs.com/hushaojun/p/7792503.html