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

About this user

Tim Morgan http://timmorgan.org

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Find & Replace in Word Document with Ruby

I use this to open a "template" (really just a plain Word document with [text to replace] inside), do the substitutions, and save as a new filename.

   1  
   2  require 'win32ole'
   3  
   4  word = WIN32OLE.new('Word.Application')
   5  #word.Visible = true # uncomment if you want to see it happen
   6  doc = word.Documents.Open('c:\file_to_open.doc')
   7  {
   8    'name' => 'Tim Morgan',
   9    'date' => Date.today.strftime('%B %d, %Y'),
  10    ...
  11  }.each do |key, value|
  12    word.Selection.HomeKey(unit=6) # start at beginning
  13    find = word.Selection.Find
  14    find.Text = "[#{key}]" # text must be in square brackets
  15    while word.Selection.Find.Execute
  16      word.Selection.TypeText(text=value)
  17    end
  18  end
  19  doc.SaveAs('c:\output_file.doc')
  20  doc.Close

Script Word from Python

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.

   1  
   2  from win32com.client import constants, Dispatch
   3  
   4  import pythoncom
   5  
   6  wdStory = 6
   7  
   8  class WordDocument(object):
   9    """
  10    Some convenience methods for Word documents accessed
  11    through COM.
  12    """
  13    
  14    def __init__(self, visible=False):
  15      self.app = Dispatch("Word.Application")
  16      self.app.Visible = visible
  17    
  18    def new(self, filename=None):
  19      """
  20      Create a new Word document. If 'filename' specified,
  21      use the file as a template.
  22      """
  23      self.app.Documents.Add(filename)
  24    
  25    def open(self, filename):
  26      """
  27      Open an existing Word document for editing.
  28      """
  29      self.app.Documents.Open(filename)
  30    
  31    def save(self, filename=None):
  32      """
  33      Save the active document. If 'filename' is given,
  34      do a Save As.
  35      """
  36      if filename:
  37        self.app.ActiveDocument.SaveAs(filename)
  38      else:
  39        self.app.ActiveDocument.Save()
  40    
  41    def save_as(self, filename):
  42      return self.save(filename)
  43    
  44    def print_out(self):
  45      """
  46      Print the active document.
  47      """
  48      self.app.Application.PrintOut()
  49    
  50    def close(self):
  51      """
  52      Close the active document.
  53      """
  54      self.app.ActiveDocument.Close()
  55    
  56    def quit(self):
  57      """
  58      Quit Word.
  59      """
  60      return self.app.Quit()
  61    
  62    def find_and_replace(self, find_str, replace_str):
  63      """
  64      Find all occurances of 'find_str' and replace with 'replace_str'
  65      in the active document.
  66      """
  67      self.app.Selection.HomeKey(Unit=wdStory)
  68      find = self.app.Selection.Find
  69      find.Text = find_str
  70      while self.app.Selection.Find.Execute():
  71        self.app.Selection.TypeText(Text=replace_str)

Script Excel from Python

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

   1  
   2  from win32com.client import constants, Dispatch
   3  import pythoncom
   4  import os
   5  
   6  borderTop = 3
   7  borderBottom = 4
   8  borderLeft = 1
   9  borderRight = 2
  10  borderSolid = 1
  11  borderDashed = 2
  12  borderDotted = 3
  13  colorBlack = 1
  14  directionUp = -4162
  15  directionDown = -4121
  16  directionLeft = -4131
  17  directionRight = -4152
  18  
  19  class ExcelDocument(object):
  20    """
  21    Some convenience methods for Excel documents accessed
  22    through COM.
  23    """
  24    
  25    def __init__(self, visible=False):
  26      self.app = Dispatch("Excel.Application")
  27      self.app.Visible = visible
  28      self.sheet = 1
  29    
  30    def new(self, filename=None):
  31      """
  32      Create a new Excel workbook. If 'filename' specified,
  33      use the file as a template.
  34      """
  35      self.app.Workbooks.Add(filename)
  36    
  37    def open(self, filename):
  38      """
  39      Open an existing Excel workbook for editing.
  40      """
  41      self.app.Workbooks.Open(filename)
  42    
  43    def set_sheet(self, sheet):
  44      """
  45      Set the active worksheet.
  46      """
  47      self.sheet = sheet
  48    
  49    def get_range(self, range):
  50      """
  51      Get a range object for the specified range or single cell.
  52      """
  53      return self.app.ActiveWorkbook.Sheets(self.sheet).Range(range)
  54    
  55    def set_value(self, cell, value=''):
  56      """
  57      Set the value of 'cell' to 'value'.
  58      """
  59      self.get_range(cell).Value = value
  60    
  61    def get_value(self, cell):
  62      """
  63      Get the value of 'cell'.
  64      """
  65      value = self.get_range(cell).Value
  66      if isinstance(value, tuple):
  67        value = [v[0] for v in value]
  68      return value
  69    
  70    def set_border(self, range, side, line_style=borderSolid, color=colorBlack):
  71      """
  72      Set a border on the specified range of cells or single cell.
  73      'range' = range of cells or single cell
  74      'side' = one of borderTop, borderBottom, borderLeft, borderRight
  75      'line_style' = one of borderSolid, borderDashed, borderDotted, others?
  76      'color' = one of colorBlack, others?
  77      """
  78      range = self.get_range(range).Borders(side)
  79      range.LineStyle = line_style
  80      range.Color = color
  81    
  82    def sort(self, range, key_cell):
  83      """
  84      Sort the specified 'range' of the activeworksheet by the
  85      specified 'key_cell'.
  86      """
  87      range.Sort(Key1=self.get_range(key_cell), Order1=1, Header=0, OrderCustom=1, MatchCase=False, Orientation=1)
  88    
  89    def hide_row(self, row, hide=True):
  90      """
  91      Hide the specified 'row'.
  92      Specify hide=False to show the row.
  93      """
  94      self.get_range('a%s' % row).EntireRow.Hidden = hide
  95    
  96    def hide_column(self, column, hide=True):
  97      """
  98      Hide the specified 'column'.
  99      Specify hide=False to show the column.
 100      """
 101      self.get_range('%s1' % column).EntireColumn.Hidden = hide
 102    
 103    def delete_row(self, row, shift=directionUp):
 104      """
 105      Delete the entire 'row'.
 106      """
 107      self.get_range('a%s' % row).EntireRow.Delete(Shift=shift)
 108    
 109    def delete_column(self, column, shift=directionLeft):
 110      """
 111      Delete the entire 'column'.
 112      """
 113      self.get_range('%s1' % column).EntireColumn.Delete(Shift=shift)
 114      
 115    def fit_column(self, column):
 116      """
 117      Resize the specified 'column' to fit all its contents.
 118      """
 119      self.get_range('%s1' % column).EntireColumn.AutoFit()
 120    
 121    def save(self):
 122      """
 123      Save the active workbook.
 124      """
 125      self.app.ActiveWorkbook.Save()
 126    
 127    def save_as(self, filename, delete_existing=False):
 128      """
 129      Save the active workbook as a different filename.
 130      If 'delete_existing' is specified and the file already
 131      exists, it will be deleted before saving.
 132      """
 133      if delete_existing and os.path.exists(filename):
 134        os.remove(filename)
 135      self.app.ActiveWorkbook.SaveAs(filename)
 136    
 137    def print_out(self):
 138      """
 139      Print the active workbook.
 140      """
 141      self.app.Application.PrintOut()
 142    
 143    def close(self):
 144      """
 145      Close the active workbook.
 146      """
 147      self.app.ActiveWorkbook.Close()
 148    
 149    def quit(self):
 150      """
 151      Quit Excel.
 152      """
 153      return self.app.Quit()
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS