欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python兼容VBA的用法詳解

 更新時間:2021年09月11日 08:57:04   作者:xue_11  
這篇文章主要介紹了python兼容VBA的用法詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

一、簡介

有時我們需要向含有VBA代碼的Excel寫入數(shù)據(jù),但又不能影響正常的VBA代碼執(zhí)行,起初我使用python的openpyxl模塊中函數(shù)將數(shù)據(jù)寫入xlsm文件中,寫入數(shù)據(jù)后發(fā)現(xiàn)執(zhí)行VBA代碼的按鈕消失不見了,于是通過查找原因發(fā)現(xiàn)是由于openpyxl對VBA支持并不友好,而對VBA支持友好是xlwings模塊。

二、簡單介紹下xlwings模塊

在這里插入圖片描述

1、讀取Excel中數(shù)據(jù)

讀取需注意點(diǎn):
默認(rèn)情況下,帶有數(shù)字的單元格被讀取為float,帶有日期單元格被讀取為datetime.datetime,空單元格轉(zhuǎn)化為None;數(shù)據(jù)讀取可以通過option操作指定格式讀取。

import xlwings as xw
import os

#創(chuàng)建APP應(yīng)用
app=xw.App(visible=True,add_book=False)    #visible表示程序運(yùn)行時是否可見Excel,True表示可見,F(xiàn)alse表示不可見;add_book表示是否要新建工作簿
file = "數(shù)據(jù)寫入V1.xlsm"
wb=app.books.open(file)                    #打開指定文件


ws = wb.sheets["Sheet1"]                   #工作表引用
#ws.activate()
temp_value = ws["B2"].value                #默認(rèn)讀取B2的值,為浮點(diǎn)型
print(type(temp_value))
print(temp_value)

temp_n = ws["B3"].value                    #默認(rèn)讀取B3的值,這里未空值默認(rèn)應(yīng)顯示None
print(type(temp_n))
print(temp_n)

temp_value1 = ws["B2"].options(numbers=int).value   #將B2的設(shè)置為整數(shù)
print(type(temp_value1))
print(temp_value1)

#運(yùn)行結(jié)果

<class 'float'>

100.0

<class 'NoneType'>

None

<class 'int'>

100

>>> 

2、另一種取值單元格值得方式

import xlwings as xw
import os

app=xw.App(visible=True,add_book=False)                
file = "數(shù)據(jù)寫入V1.xlsm"
wb=app.books.open(file)                      #打開指定文件
ws = wb.sheets["Sheet1"]
print(ws.range('B2').value)                  #另一種方式讀取B2的值
#運(yùn)行結(jié)果
100.0

三、將數(shù)據(jù)寫入Excel

在這里插入圖片描述

import xlwings as xw
import os

#創(chuàng)建APP應(yīng)用
app=xw.App(visible=True,add_book=False)                
file = "數(shù)據(jù)寫入V1.xlsm"
wb=app.books.open(file)                      #打開指定文件

#工作表引用
ws = wb.sheets["Sheet1"]
a = 6799
b = 2345
c = 1000
info = ws.used_range
#print(info)
nrows = info.last_cell.row             #獲取sheet表中最大行
print(nrows)
if ws['B'+str(nrows)]==None:
    ws['B'+str(int(nrows)-1)].value=a
    ws['C'+str(int(nrows)-1)].value=b
    ws['D'+str(int(nrows)-1)].value=c
else:
    ws['B'+str(int(nrows)+1)].value=a
    ws['C'+str(int(nrows)+1)].value=b
    ws['D'+str(int(nrows)+1)].value=c
    
wb.save()                  #保存數(shù)據(jù)
wb.close()                 #關(guān)閉工作簿
app.quit()                

寫入后

在這里插入圖片描述

到此這篇關(guān)于python兼容VBA的用法詳解的文章就介紹到這了,更多相關(guān)python兼容VBA的用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論