1+ import xlwings as xw
2+ import matplotlib .pyplot as plt
3+ import pandas as pd
4+ import numpy as np
5+
6+
7+ # 打开已保存的 Excel
8+ def open_excel ():
9+ file_path = r'G:/test/test.xlsx'
10+
11+ wb = xw .Book (file_path ) # 固定打开表格
12+ # xw.books.open(file_path) # 频繁打开表格
13+
14+ # 引用表空间
15+ sht = wb .sheets ['sheet1' ]
16+
17+ # 引用单元格
18+ rng = xw .Range ('A1' )
19+ # rng = sht['a1']
20+ # rng = sht[0,0] 第一行的第一列即a1,相当于pandas的切片
21+
22+ # 引用区域
23+ # rng = sht.range('a1:a5')
24+ # rng = sht['a1:a5']
25+ # rng = sht[:5,0]
26+
27+ xw .Book (file_path ).sheets [0 ].range ('A1:D5' )
28+
29+ # 写入数据
30+ sht .range ('A1' ).value = 'Hello Excel'
31+
32+ sht .range ('A1' ).value = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
33+
34+ # 按照列写入数据
35+ sht .range ('A2' ).options (transpose = True ).value = [2 , 3 , 4 , 5 , 6 , 7 , 8 ]
36+
37+ # 二维列表写入数据
38+ sht .range ('A9' ).expand ('table' ).value = [['a' , 'b' , 'c' ], ['d' , 'e' , 'f' ], ['g' , 'h' , 'i' ], ['j' , 'k' , 'l' ]]
39+
40+ print (sht .range ('A1:D5' ).value )
41+
42+ wb .save ()
43+
44+ #def read_data():
45+
46+ if __name__ == '__main__' :
47+ #open_excel()
48+
49+ fig = plt .figure () # 指定画布
50+ # plt.plot([1, 2, 3, 4, 5])
51+ plt .plot ([36 ,5 ,3 ,25 ,78 ])
52+ plt .plot ([9 ,10 ,31 ,45 ])
53+ plt .plot ([6 ,14 ,45 ,31 ])
54+ sht = xw .Book (r'G:/test/test.xlsx' ).sheets [0 ]
55+ sht .pictures .add (fig , name = 'myplt' , update = True )
0 commit comments