Feeds

Quick scripting for .NET with IronPython

Office benefits

5 things you didn’t know about cloud backup

Rather than continue to use the interactive shell, it's time to write some code so create a text file called wkbs.py. The first thing is to put in place the code we need to grab the path from the command line, or else fall back on a suitable hard-coded default. It also lists the files that it finds for us:


import sys
sys.path.append(r'c:\Python25\lib')

import glob
import os.path
from System.IO import File, FileInfo

if __name__ == '__main__':
  if len(sys.argv)==2:
    wkbdir=sys.argv[1]
  else:
    wkbdir=r'c:\spreadsheets\*.xls*'

wkbs=glob.glob(wkbdir)
print wkbs

Run this by typing ipy wkbs.py <your path> at the command prompt.

Not very interesting yet, and no sign of .NET. So let's make use of some libraries from the System.IO package. Going back to the code let's define a function that lists the workbook name and last accessed date. Add the following to the end of wkbs.py:


def wkbInfo2(w):
  print 'Name: %s, Last Accessed: %s' % (FileInfo(w).Name, File.GetLastAccessTime(w))
  return w

names=[wkbInfo2(wkb) for wkb in wkbs ]
print 'Total files : %d' % len(names)

This prints out the name and last accessed timestamp of each file, along with a count of found files at the end.

But we want more than this, we want to know the number of worksheets and the name of each sheet as well. For this we need to open each workbook in Excel, walk the worksheets collection and then exit cleanly.


def wkbInfo3(w):
  ewb=excel.Workbooks.Open(w)
  print "Name: %s, Number of worksheets: %s" % (ewb.Name, ewb.Worksheets.Count)
  for bk in ewb.Worksheets:
    print '\tSheetName: ' + bk.Name
  ewb.Close(False)
  ewb=None
  return w

import clr
import System
print '\nLinking to Excel...'
clr.AddReference("Microsoft.Office.Interop.Excel")
import Microsoft.Office.Interop.Excel as Excel

excel = Excel.ApplicationClass()
names=[wkbInfo3(wkb) for wkb in wkbs ]
print 'Total files : %d' % len(names)
excel.Quit()
excel=None

Note the house keeping in that code, explicitly setting the workbook and application classes to None to ensure that references are released. Failure to do so means that you can end up with a rogue (and invisible) Excel instance running in the background after the program has finished executing.

As should be clear, IronPython provides a good environment for quickly knocking up scripts that can make full use of existing .NET classes and packages. Even relatively tricky things, like grabbing hold of an Office application, can be accomplished easily enough.

The examples so far, though, are console applications coded in a simple text editor. What if you want something in the way of a GUI? And you want more than notepad? In part two we'll look at IronPythonStudio to see what it's got to offer.®

Boost IT visibility and business value

More from The Register

next story
Intel's Raspberry Pi rival Galileo can now run Windows
Behold the Internet of Things. Wintel Things
The Return of BSOD: Does ANYONE trust Microsoft patches?
Sysadmins, you're either fighting fires or seen as incompetents now
Munich considers dumping Linux for ... GULP ... Windows!
Give a penguinista a hug, the Outlook's not good for open source's poster child
Microsoft cries UNINSTALL in the wake of Blue Screens of Death™
Cache crash causes contained choloric calamity
Eat up Martha! Microsoft slings handwriting recog into OneNote on Android
Freehand input on non-Windows kit for the first time
Linux kernel devs made to finger their dongles before contributing code
Two-factor auth enabled for Kernel.org repositories
prev story

Whitepapers

5 things you didn’t know about cloud backup
IT departments are embracing cloud backup, but there’s a lot you need to know before choosing a service provider. Learn all the critical things you need to know.
Implementing global e-invoicing with guaranteed legal certainty
Explaining the role local tax compliance plays in successful supply chain management and e-business and how leading global brands are addressing this.
Build a business case: developing custom apps
Learn how to maximize the value of custom applications by accelerating and simplifying their development.
Rethinking backup and recovery in the modern data center
Combining intelligence, operational analytics, and automation to enable efficient, data-driven IT organizations using the HP ABR approach.
Next gen security for virtualised datacentres
Legacy security solutions are inefficient due to the architectural differences between physical and virtual environments.