xlwings1 快速入門

2022-07-27 20:54:14 字數 2928 閱讀 2792

前言:安裝

pip install xlwings

xlwings 安裝成功後,如果執行提示報錯「importerror: no module named win32api」,請再安裝 pypiwin32 或者 pywin32 包;(pip install pypiwin32)

1、指令碼:自動化/與python的excel互動

建立工作薄或開啟現有工作簿

import

xlwings as xw

wb = xw.book() #

這句建立乙個新的工作薄

wb = xw.book('

filename.xlsx

') #

連線到當前工作目錄中的現有檔案

wb = xw.book(r'

c:\path\to\file.xlsx

') #

在windows上:使用原始字元r來避免反斜轉義

如果開啟了多個檔案可以用下面的語句來獲取物件:

filename

']

import

xlwings as xw

工作簿1']

sht = wb.sheets[0]

例項化乙個表物件:

sht = wb.sheets['

sheet1']

sht = wb.sheets[0]

非常容易的讀取單元格的值,或將值寫入單元格

sht.range("

a1").value = "

foo1"#

將值寫入單元格

v = sht.range("

a1").value #

讀取excel的值

print(v) #

列印結果:foo1

有許多方便的特性,例如:單元格範圍擴充套件

sht.range('

a1').value = [['

foo 1

', '

foo 2

', '

foo 3

'], [10.0, 20.0, 30.0]] #

將列表或元組中的資料寫入單元格區域

sht.range('

a1').value = [('

foo 1

', '

foo 2

', '

foo 3

'), (10.0, 20.0, 30.0)] #

將列表或元組中的資料寫入單元格區域

sht.range('

a1').value = [('

foo 1

', '

foo 2

', '

foo 3

'), (10.0, 20.0, 30.0)] #

將列表或元組中的資料寫入單元格區域

v = sht.range('

a1').expand().value #

讀取單元格a1所在的區域的值

print(v)

快捷操作活動單元格

如果您希望快速地與活動工作簿中的活動表對話,您不需要例項化工作簿和表單物件,但可以簡單的按下面**做:

import

xlwings as xw

xw.range("a1

").value = '

foo1'#

一定注意這個range是大寫開頭的,而例項話物件的是小寫的

v = xw.range("

a1").value

2、巨集命令:從excel中呼叫python1)在vba中呼叫python首先要安裝外掛程式,在windows中開啟cmd命令列輸入:xlwings addin install

2)安裝成功後,在vba編輯視窗,選單欄中的工具——引用,然後選擇 

可以使用runpython函式從vba呼叫python函式。

sub helloworld()

runpython (

"import hello; hello.world()")

end sub

在預設情況下,runpython期望.py檔案與excel檔案在相同的目錄中。通過使用xw.book.caller來獲取工作簿物件。

#

hello.py

#import numpy as np

import

xlwings as xw

defworld():

wb =xw.book.caller()

wb.sheets[0].range('a1

').value = '

hello world!

'

3、自定義函式:使用者自定義函式(只限windows)寫乙個使用者自定義函式是很簡單的:

import

xlwings as xw

@xw.func

defhello(name):

return

'hello

'.format(name)

要求excel**的名字必須和.py的名字相同才能匯入,否則會報錯

xlwings1 多執行緒寫入excel資料

ufr bin env python coding utf 8 import xlwings as xw import queue import threading import time stopevent object class treadpool def init self,max num,...

快速入門1

快速入門 一 資料型別和變數 1 number 2 字串 3 布林值 true false 布林運算 4 比較運算子 相等運算子 5 陣列 1 1,2,3.14,hello null 2 6 物件 鍵和值組成的無序集合 var person person的name屬性為 bob 要獲取乙個物件的屬性...

Rop快速入門(1)

1.什麼是rop 2.rop的整體框架 rop的重點在應用層,無論是對於各個模型的封裝,都是很好的解決的傳統框架難以達到的效果,減小開發者對於公共模組的開發量,從而將能力注意轉移到業務方面,同時我們可以看出,rop框架也充分借鑑了spring mvc的設計,下面這張圖為大家展示rop技術框架 客戶端...