python操作Excel word

來源:互聯網
上載者:User

跟網上其他的程式是一樣的,這裡分別增加了一個全域替換的函數。

可以進行整個文檔的替換,這樣可以實現翻譯,查錯等全域替換的操作。

# -*- coding: utf-8 -*-

import os,types,pickle
from win32com.client import Dispatch

import win32com.client

class Excel:
    """A utility to make it easier to get at Excel."""

    def __init__(self, filename=None):
        self.xlApp = win32com.client.Dispatch('Excel.Application')
        self.xlApp.Visible = False
        self.xlApp.DisplayAlerts = False  #搜尋不到時不提示對話方塊
        
        if filename:
          self.filename = filename
          self.xlBook = self.xlApp.Workbooks.Open(filename)
        else:
          self.xlBook = self.xlApp.Workbooks.Add()
          self.filename = '' 

    def save(self, newfilename=None):
      if newfilename:
          self.filename = newfilename
          self.xlBook.SaveAs(newfilename)
      else:
          self.xlBook.Save()
          
    def close(self):
        self.xlBook.Close(SaveChanges=0)
        del self.xlApp

    def getCell(self, sheet, row, col):
        "Get value of one cell"
        sht = self.xlBook.Worksheets(sheet)
        return sht.Cells(row, col).Value

    def getCell(self, sheetindex, row, col):
        "Get value of one cell"
        sht = self.xlBook.Worksheets(sheetindex)
        return sht.Cells(row, col).Value

    def setCell(self, sheet, row, col, value):
        "set value of one cell"
        sht = self.xlBook.Worksheets(sheet)
        sht.Cells(row, col).Value = value

    def setCell(self, sheetindex, row, col, value):
        "set value of one cell"
        sht = self.xlBook.Worksheets(sheetindex)
        sht.Cells(row, col).Value = value

    def getRange(self, sheet, row1, col1, row2, col2):
        "return a 2d array (i.e. tuple of tuples)"
        sht = self.xlBook.Worksheets(sheet)
        return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value

    def addPicture(self, sheet, pictureName, Left, Top, Width, Height):
        "Insert a picture in sheet"
        sht = self.xlBook.Worksheets(sheet)
        sht.Shapes.AddPicture(pictureName, 1, 1, Left, Top, Width, Height)

    def cpSheet(self, before):
        "copy sheet"
        shts = self.xlBook.Worksheets
        shts(1).Copy(None,shts(1))
      
    def getUsedRange(self, sheetindex):
        sht = self.xlBook.Worksheets(sheetindex)  
        return sht.UsedRange.Rows.Count,sht.UsedRange.Columns.Count

    def getSheetCount(self):
        return self.xlBook.sheets.Count

    def replace(self, sheetindex, oldStr, newStr):
        """Find the oldStr and replace with the newStr.
        """
        #Replace(oldStr, newStr, LookAt, SearchOrder, MatchCase, MatchByte, SearchFormat, ReplaceFormat)
        # print self.xlBook.Worksheets(sheetindex).Name
        #self.xlBook.Worksheets(sheetindex).Activate   #activate the current sheet
        #self.xlApp.Selection.Replace(oldStr, newStr)   #replace only activate sheet

        sht = self.xlBook.Worksheets(sheetindex)
        sht.Cells.Replace(oldStr, newStr) #replace every sheet

class Word:
    "A utility to make it easier to get at Word."
    def __init__(self, filename=None):
        self.wdApp = Dispatch('Word.Application')
        #預設文件不可見
        self.wdApp.Visible = False
        
        if filename:
              self.filename = filename
              self.workBook = self.wdApp.Documents.Open(filename)
        else:
              self.workBook =  self.wdApp.Documents.Add()
              self.filename = '' 
       
    def visible(self, visible=True):
        self.wdApp.Visible = visible

    def find(self, text, MatchWildcards=False):
        "find text"
        find = self.wdApp.Selection.Find
        find.ClearFormatting()
        find.Execute(text,  False,  False,  MatchWildcards,  False,  False,  True,  0)
        return self.wdApp.Selection.Text
        
    def replaceAll(self, oldStr, newStr):
        """Find the oldStr and replace with the newStr.
        """
        find = self.wdApp.Selection.Find
        find.ClearFormatting()
        find.Replacement.ClearFormatting()
        find.Execute(oldStr,  False,  False,  False,  False,  False,  True,  1,  True,  newStr,  2)   

    def updateToc(self):
        for tocitem in self.wdApp.ActiveDocument.TablesOfContents:
                 tocitem.Update()

    def save(self):
        "Save the active document"
        self.wdApp.ActiveDocument.Save()

    def saveAs(self, filename, delete_existing=True):
        """
        Save the active document as a different filename.
        If 'delete_existing' is specified and the file already
        exists,  it will be deleted before saving.
        """
        if delete_existing and os.path.exists(filename):
                 os.remove(filename)
        self.wdApp.ActiveDocument.SaveAs(FileName=filename)

    def close(self):
        "Close the active workbook. "
        self.wdApp.ActiveDocument.Close()
         
    def quit(self):
        " Quit Word"

        return self.wdApp.Quit()

《完》

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.