python3 讀取寫入excel操作-win32com


前面有寫一篇是用xlrd操作excel的,這一篇是使用win32com來進行操作excel,個人推薦使用win32com。

要使用win32com組件,也需要先導入win32com包。

 

 

# -*- coding:utf-8 -*-
__author__ = u'harry'

import win32com
from win32com.client import Dispatch,constants
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))# Excel表格中測試結果底色
OK_COLOR = 0xffffff
False_COLOR = 0xff
# NT_COLOR=0xffff
NT_COLOR = 0xC0C0C0

# Excel表格中測試結果匯總顯示位置
TESTTIME = [1, 14]
TESTRESULT = [2, 14]

# Excel模版設置
# self.titleindex=3        #Excel中測試用例標題行索引
# self.casebegin =4        #Excel中測試用例開始行索引
# self.argbegin   =3       #Excel中參數開始列索引
# self.argcount  =8        #Excel中支持的參數個數
class excel():
    # def __init__(self, sFile, dtitleindex=3, dcasebegin=4, dargbegin=3, dargcount=8):
    def __init__(self, sFile):
        self.xlApp = win32com.client.Dispatch('Excel.Application')  # MS:Excel  WPS:et
        try:
            self.book = self.xlApp.Workbooks.Open(sFile)
        except:
            print(u"打開文件失敗")
            exit()

    def close(self):
        # self.book.Close(SaveChanges=0)
        #self.book.Save()
        self.book.Close(SaveChanges=0)
        # self.xlApp.Quit()
        del self.xlApp

    def read(self, iSheet, iRow, iCol):
        try:
            sht = self.book.Worksheets(iSheet)
            sValue = str(sht.Cells(iRow, iCol).Value)
        except:
            self.close()
            print(u'讀取數據失敗')
            exit()
            # 去除'.0'
        if sValue[-2:] == '.0':
            sValue = sValue[0:-2]
        return sValue

    def write(self, iSheet, iRow, iCol, sData):
        try:
            sht = self.book.Worksheets(iSheet)
            sht.Cells(iRow, iCol).Value = sData  # .decode("utf-8")
            if sData == "Failed":
                sht.Cells(iRow, iCol).Interior.Color = False_COLOR
                self.book.Save()
            else:
                sht.Cells(iRow, iCol).Interior.Color = OK_COLOR
                self.book.Save()
        except Exception:
            self.close(SaveChanges=0)
            print(u'寫入數據失敗:'+Exception)
            exit()

'''
excelpath = 'D:\\python\\DATA\\TestCase1.xls'
test = excel(excelpath)
test.write(2, 11, 7,"aaa")
test.close()
'''

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM