python操作Excel word

来源:互联网 发布:在党规党纪面前知敬畏 编辑:程序博客网 时间:2024/05/03 11:36

跟网上其他的程序是一样的,这里分别增加了一个全局替换的函数。

可以进行整个文档的替换,这样可以实现翻译,查错等全局替换的操作。


# -*- 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()


《完》

原创粉丝点击