Skip to content

Instantly share code, notes, and snippets.

@wirewc
Created August 5, 2014 16:03
Show Gist options
  • Save wirewc/343e0de2233f1893b430 to your computer and use it in GitHub Desktop.
Save wirewc/343e0de2233f1893b430 to your computer and use it in GitHub Desktop.
Python27 Microsoft Excel functions
"""This script is an example of simple read and write functions to a spreadsheet. One may import these features
into their own programs or use them as an example for using the COM interface in Python.
This is quite possibly the most useful code I have ever written to facilitate automated testing or code
generation in a windows environment. Please let me know where this code gets used so I can keep a small
record of other people it has helped =D.
Writen by William Christensen, wirewc@gmail.com
"""
from win32com.client import Dispatch
def read(columns,rows,columnOffset=0,rowOffset=0,sheets=0):
"""Function takes arguments for rows, columns, and the left most corner of the data.
Use default value (0) for the active sheet or list a number to specify otherwise.
This function returns a list array of the data."""
xl = Dispatch("Excel.Application")
myArray = []
for i in range(rows):
tempL = []
for j in range(columns):
if (sheets ==0):
tempL.append(xl.ActiveWorkbook.ActiveSheet.Cells(i+rowOffset+1,j+columnOffset+1).Value)
else:
tempL.append(xl.ActiveWorkbook.Sheets(sheets).Cells(i+rowOffset+1,j+columnOffset+1).Value)
myArray.append(tempL)
del tempL
return myArray
def write(data,column=0,row=0,sheet=0):
"""Writes first argument to any cell. Use default value to use the active sheet or specify the sheet number."""
xl = Dispatch("Excel.Application")
## xl.ActiveWorkbook.Sheets(sheet).Cells(column,row).Value = data
if (sheet == 0):
xl.ActiveWorkbook.ActiveSheet.Cells(column+1,row+1).Value=data
else:
xl.ActiveWorkbook.Sheets(sheet).Cells(column+1,row+1).Value=data
del xl
def writeArray(data,columnOffset=0,rowOffset=0,sheet=0,):
"""Writes an array (first argument) to an excel spreadsheet. Other arguments are used to shift the
array to the right and how far down from the first cell (A1). Use the default value to use the active
sheet or specify the sheet number that you wish to write too."""
xl = Dispatch("Excel.Application")
for i in range(len(data)):
for j in range(len(data[i])):
## xl.ActiveWorkbook.Sheets(sheet).Cells(i+rowOffset+1,j+columnOffset+1).Value=data[i][j] # original function for writing the array.
if (sheet ==0):
xl.ActiveWorkbook.ActiveSheet.Cells(i+rowOffset+1,j+columnOffset+1).Value=data[i][j]
else:
xl.ActiveWorkbook.Sheets(sheet).Cells(i+rowOffset+1,j+columnOffset+1).Value=data[i][j]
del xl
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment