使用Excel时,软件自带的公式有时候不能满足需要,可以使用Python的xlwings在Excel中添加新的公式。
1. 安装xlwings
>pip install xlwings
>xlwings addin install
2. Excel设置
首先调出“开发工具”菜单,“文件”--> 选项 --> 自定义功能区 --> 主选项卡,设置如下:
设置引用xlwings:
开发工具--> Visual Basic --> 工具 --> 引用 :
Excel的Xlwings主选项卡中如果不勾选“Show Console”时需要设置Interpreter为pythonw.exe。
3. 操作示例,编写python程序,py文件名要和Excel文件名一样,并将Excel另存为包含宏的工作表(.xlsm):
# _*_ coding: utf-8 _*_
import xlwings as xw
@xw.func
def width_before_cutting(cut_size):
#打开当前调用工作簿
wb = xw.Book.caller()
#打开外部工作簿
#wb = xw.Book(r"D:\production_list_template.xlsx")
sht_cut = wb.sheets['cutting_size']
cut_list = sht_cut.range('B2').expand('down').value
width_bef_cut = sht_cut.range('F2').expand('down').value
cut_index_c = cut_list.count(cut_size)
if (cut_index_c == 0):
return "Not Found Cutting Size"
else:
if (cut_index_c >= 2 ):
return "Too Much size selections"
else:
return width_bef_cut[cut_list.index(cut_size)]
修改py文件后需使用”Import Functions”刷新公式。
xlwings需要打开Excel文件是不可避免的,app = xw.App(visible=True, add_book=False)命令只是隐藏了GUI窗口,查任务管理器里会有打开的excel程序,而且还会出现诡异的弹出很多空白文档的问题。故上述程序在运行前需打开调用的Excel文件,避免出错。
可以在py文件中调用openpyxl来执行只读文件的操作,避免上面的问题,还加快了运行速度。示例如下:
import xlwings as xw
import openpyxl as xl
#利用xw.func来实现Excel中的程序调用
@xw.func
def width_before_cutting(cut_size):
wb = xl.load_workbook("D:\works\production_list1.xlsx")
sht_cut = wb['cutting_size']
cut_list = []
width_list = []
rows = sht_cut.max_row
for i in range(2, rows+1):
cell_value1 = sht_cut.cell(row=i, column=2).value
cell_value2 = sht_cut.cell(row=i, column=6).value
cut_list.append(cell_value1)
width_list.append(cell_value2)
width_index_c = cut_list.count(cut_size)
if (width_index_c == 0):
return "Not Found!!"
else:
if (width_index_c >= 2 ):
return "Too Much Choices"
else:
return width_list[cut_list.index(cut_size)]
wb.close()