Skip to content

Commit

Permalink
added xldb.timeseries_toXLS function
Browse files Browse the repository at this point in the history
  • Loading branch information
bart mosley committed Sep 19, 2011
1 parent a9f7f94 commit 9852bf6
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions xldb.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,27 @@
Created on Apr 17, 2010
@author: bartmosley
Utility functions:
xl_to_date
xlValue
Classes:
XLSBook
XLdb
XLOut
Factory functions:
timeseries_toXLS
'''
import os
import xlrd
import xlwt

from urllib2 import urlopen
from datetime import date, timedelta
from tempfile import mkstemp

def xl_to_date(xdate, _datemode = 1):
yyyy, mm, dd, h, m, s =xlrd.xldate_as_tuple(xdate.value, _datemode)
Expand Down Expand Up @@ -221,6 +235,7 @@ def column(self, columnName, reduce=True):
def xlCellValue(self, x):
return xlValue(x, self.datemode, self.hash_comments)


class XLOut(object):
'''
Creates a workbook object for writing. Defines a dict of cell formats,
Expand Down Expand Up @@ -293,3 +308,63 @@ def freezepanes(self, row_, col_, sheet=0):

def save(self):
self.wkb.save(self.filename)


def timeseries_toXLS(xdata, fname=None, fdir=None, hdr=None):
'''
Writes Timeseries data to a spreadsheet.
xdata: a dict object, {date_key: value}, where the key is assumed to
be a datetime.date object. 'value' is either a single value or
a tuple (value1, value2, value3)
fname: filename, if not provided a temporary filename is used. filename
extension will be changed to .xls
fdir: directory in which to create the file. If not provided 'fname'
is taken to be the full path, or if a temporary filename is created
the file is placed in a default directory
hdr: column headings, if not provided ['data', 'value1', ...]
'''

# use tempfile.mkstemp to create file name if not provided
if not fname:
fd, fpath = mkstemp(dir=fdir, suffix=".xls")
os.close(fd)
else:
# make sure file ends with .xls extension
fname = '.'.join((fname.split('.')[0], "xls"))
fpath = os.path.join(fdir if fdir else '', fname)

wkb = XLOut(fpath)

date_keys = xdata.keys()
date_keys.sort()

# create header if not provided
if not hdr:
testdata = xdata[date_keys[0]]
hdr = ['date']
try:
hdr.extend(['value'+str(n) for n in range(1, len(testdata))+1])

except:
hdr.append('value1')

# write header row
for ncol in range(len(hdr)):
wkb.write(hdr[ncol], 0, ncol, 0)

# write data rows
for nrow, dt in enumerate(date_keys, start=1):
wkb.write(dt, nrow, 0, 0, format='date')

for ncol in range(1, len(hdr)):
value = xdata[dt]
wkb.write(value, nrow, ncol, format=hdr[ncol][1])

wkb.save()

return fpath

0 comments on commit 9852bf6

Please sign in to comment.