It turns out that this nifty pyExcelerator program will let you write an Excel formatted document directly from Python.
While you could always use COM automation with the Python Win32 extensions to make Excel documents, I think this library is the way to go. It lets you write an Excel file without even having to have Excel installed, and you don’t even need to be running on Windows. That’s pretty neat. It sounds like an easy way to offer an Excel output format option from your application or website, without requiring any messing with Windows or Excel.
Sadly there wasn’t any friendly documentation for this project online, so here I offer my first code snippet using this package. I mostly figured it out from the example files included with the package. It writes a few rows of data and styles the data depending on content.
import pyExcelerator as xl
def save_in_excel(headers,values):
#Open new workbook
mydoc=xl.Workbook()
#Add a worksheet
mysheet=mydoc.add_sheet("test")
#write headers
header_font=xl.Font() #make a font object
header_font.bold=True
header_font.underline=True
#font needs to be style actually
header_style = xl.XFStyle(); header_style.font = header_font
for col,value in enumerate(headers):
mysheet.write(0,col,value,header_style)
#write values and highlight those that match my criteria
highlighted_row_font=xl.Font() #no real highlighting available?
highlighted_row_font.bold=True
highlighted_row_font.colour_index=2 #2 is red,
highlighted_row_style = xl.XFStyle(); highlighted_row_style.font = highlighted_row_font
for row_num,row_values in enumerate(values):
row_num+=1 #start at row 1
if row_values[1]=='Manatee':
for col,value in enumerate(row_values):
#make Manatee's (sp) red
mysheet.write(row_num,col,value,highlighted_row_style)
else:
for col,value in enumerate(row_values):
#normal row
mysheet.write(row_num,col,value)
#save file
mydoc.save(r'C:testpyexel.xlt')
headers=['Date','Name','Localatity']
data=[
['June 11, 2006','Greg','San Jose'],
['June 11, 2006','Greg','San Jose'],
['June 11, 2006','Greg','San Jose'],
['June 11, 2006','Greg','San Jose'],
['June 11, 2006','Manatee','San Jose'],
['June 11, 2006','Greg','San Jose'],
['June 11, 2006','Manatee','San Jose'],
]
save_in_excel(headers,data)
Here’s what my file ended up looking like:

Tags: Excel, Python, Python Excel, Excel Format, pyExcelerator
Posted by Greg Pinero (Primary Searcher) in Python, Excel
RSS 2.0