Python中,新增寫入資料到已經存在的Excel檔案
阿新 • • 發佈:2019-02-13
pip install xlrd #讀取excle
pip install xlwt #寫入excle
pip install xlutils #操作 Excel 檔案的實用工具,如複製、分割、篩選等
2.程式碼主要部分實現
import xlrd
import xlwt
from xlutils.copy import copy
dir = os.path.abspath('.').split('src')[0]
'''主要邏輯實現'''
oldWb = xlrd.open_workbook(dir+"/data/考勤系統/考勤系統.xlsx" );#先開啟已存在的表
newWb = copy(oldWb)#複製
newWs = newWb.get_sheet(2);#取sheet表
newWs.write(2, 4, "pass");#寫入 2行4列寫入pass
newWb.save(dir+"/result/考勤系統.xls"); #儲存至result路徑
3.加入寫入樣式
#建立一個樣式----------------------------
style = XFStyle()
pattern = Pattern()
pattern.pattern = Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = Style.colour_map['red'] #設定單元格背景色為黃色
style.pattern = pattern
#-----------------------------------------
部分程式碼:
xpath="html/body/div[1]/div/div/div/div[2]/h4"
if self.isElementExist(xpath):
text1 = self.driver.find_element_by_xpath(xpath).text
if text1 == except1:
newWs.write (rows, 5, "pass");
else:
newWs.write(rows, 5, "fail",style = style); ###樣式引用
else:
logger.error("沒找到元素" )
結果顯示: