天天看點

python操作表格-Python使用xlwings來操作表,python,表格

# -*- coding: UTF-8 -*-

##庫安裝的教程:包含mac和windows

#https://zhuanlan.zhihu.com/p/107086691

import xlwings as xw

#建立excel執行個體,打開Excel

app = xw.App(visible = True,add_book = False)

#打開工作簿

target = app.books.open(r"/Users/jeremiahyuan/Desktop/11.xls")

source = app.books.open(r"/Users/jeremiahyuan/Desktop/22220191129.xls")

#在工作簿中打開工作表

sht_data = source.sheets["sheetname"]

ID_xz = "aaa"

ID_gx = "bbb"

#配合for循環用下标讀取工作表設定的變量

n = 1

#循環範圍需手動修改

for i in range(4,160):

#擷取原資料中身份證号,與戶主關系,電話,姓名

sfz = sht_data.range("I"+str(i)).value

gx = sht_data.range("K"+str(i)).value

tel = sht_data.range("AA"+str(i)).value

name = sht_data.range("H"+str(i)).value

print(sfz, gx, tel, name)

if ((sht_data.range("E"+str(i)).value == ID_xz) and (sht_data.range("K"+str(i)).value == ID_gx)):

#根據下标擷取工作表

sht = target.sheets["Sheet" + str(n)]

#下面的資料是隻在為戶主的時候填寫的

print (str(i) + ":enter if")

sht.range("C3").value = "xxxxx"+ID_xz

#修改工作表名稱

sht.name = name

#擷取資料複制到新的表的對應位置

sht.range("C4").value = name

sht.range("B9").value = name

sht.range("A9").value = gx

#身份證号碼前加"""可以完美複制

sht.range("C9").value = """+sfz

sht.range("F4").value = tel

#n遞增進入下一戶人家

n+= 1

#m重新指派1

m = 1

else:

print ("enter else")

#擷取資料複制到新的表的對應位置

sht.range("B"+str(m+9)).value = name

sht.range("A"+str(m+9)).value = gx

sht.range("C"+str(m+9)).value = """+sfz

m+= 1

target.save()

target.close()

source.close()

app.quit()