Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Script Word from Python (See related posts)

A quick and dirty class for working with Word via COM in Python. By far, not all of the power of Word is available here, but it's a good start for simple tasks.

from win32com.client import constants, Dispatch

import pythoncom

wdStory = 6

class WordDocument(object):
  """
  Some convenience methods for Word documents accessed
  through COM.
  """
  
  def __init__(self, visible=False):
    self.app = Dispatch("Word.Application")
    self.app.Visible = visible
  
  def new(self, filename=None):
    """
    Create a new Word document. If 'filename' specified,
    use the file as a template.
    """
    self.app.Documents.Add(filename)
  
  def open(self, filename):
    """
    Open an existing Word document for editing.
    """
    self.app.Documents.Open(filename)
  
  def save(self, filename=None):
    """
    Save the active document. If 'filename' is given,
    do a Save As.
    """
    if filename:
      self.app.ActiveDocument.SaveAs(filename)
    else:
      self.app.ActiveDocument.Save()
  
  def save_as(self, filename):
    return self.save(filename)
  
  def print_out(self):
    """
    Print the active document.
    """
    self.app.Application.PrintOut()
  
  def close(self):
    """
    Close the active document.
    """
    self.app.ActiveDocument.Close()
  
  def quit(self):
    """
    Quit Word.
    """
    return self.app.Quit()
  
  def find_and_replace(self, find_str, replace_str):
    """
    Find all occurances of 'find_str' and replace with 'replace_str'
    in the active document.
    """
    self.app.Selection.HomeKey(Unit=wdStory)
    find = self.app.Selection.Find
    find.Text = find_str
    while self.app.Selection.Find.Execute():
      self.app.Selection.TypeText(Text=replace_str)

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts