2019年11月28日 星期四
python xlwings初體驗
import xlwings as xw
import time
wait_second = 1
## 以下新增 workbook 功能沒有成功, 先mark begin
#workbook = xw.books.add()
#workbook.name='xlwing_sample'
#workbook = xw.books.add.Book('xlwing_sample')
## 以上新增 workbook 功能沒有成功, 先mark end
app = xw.App() ## 預設會開啟一個工作本
workbook = app.books.open('xlwings_1.xlsx') ## 開啟舊工作本
app.books[0].close() ## 把 預設的工作本關掉, 否則劃面底下會多一個工作本.
sheet = workbook.sheets['工作表1']
sheet.activate()
sheet.clear()
time.sleep(wait_second)
sheet.cells(1,1).value = 'Hello World!'
sheet.cells(1,1).color = (255,0,0)
time.sleep(wait_second)
sheet.cells(1,1).color = None
sheet.cells(2,'B').value = 'Hello World AGAIN !'
sheet.cells(2,'B').color = (255,0,0)
time.sleep(wait_second)
if workbook.sheets.count == 1: ## 原要用 sheet name 找, 但會出錯, 故改為用 count.
#if workbook.sheets['工作表2'] == None:
sheet2 = workbook.sheets.add('second')
else:
sheet2 = workbook.sheets['second']
sheet2.activate()
sheet2.clear()
sheet2.cells(1,1).value = 'Sheet2 Hello World!'
sheet2.cells(1,1).color = (255,0,0)
time.sleep(wait_second)
sheet2.cells(1,1).color = None
sheet2.cells(2,'B').value = 'Sheet2 Hello World AGAIN !'
sheet2.cells(2,'B').color = (255,0,0)
time.sleep(wait_second)
workbook.save()
workbook.close()
app.quit() ## 要加這指令, 否則會卡一個空工作本在劃面上
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言