Skip to content

Instantly share code, notes, and snippets.

@carlozamagni
Last active August 29, 2015 13:57
Show Gist options
  • Save carlozamagni/9467371 to your computer and use it in GitHub Desktop.
Save carlozamagni/9467371 to your computer and use it in GitHub Desktop.
from lib import xlwt
__author__ = 'cazamagni'
class ExcelDumper(object):
def __init__(self):
self.workbook = xlwt.Workbook(encoding='utf-8')
self.sheet = self.workbook.add_sheet('Sheet1')
def write_matrix_to_sheet(self, headings, matrix):
matrix_rows, matrix_columns = len(matrix[0]), len(matrix)
# write headings
for k in range(len(headings)):
self.sheet.write(0, k, self._safe_get_vector_cell(headings, k))
# write matrix
for i in range(matrix_rows):
for j in range(matrix_columns):
# row, col, value
self.sheet.write(i+1, j, self._safe_get_matrix_cell(matrix, i, j))
self.workbook.save("file.xls")
@staticmethod
def _safe_get_matrix_cell(matrix, row, col):
try:
return matrix[col][row]
except IndexError, e:
return ''
@staticmethod
def _safe_get_vector_cell(vector, index):
try:
return vector[index]
except IndexError, e:
return ''
'''
Just a stupid test
'''
class TestExcelDump(unittest.TestCase):
matrix = [['a', 2, 3, 4, 5, 6],
[1, 'b', 3, 4, 5, 6],
[1, 2, 'c', 4, 5, 6],
[1, 2, 3, 'd', 5, 6],
[1, 2, 3, 4, 'e', 6],
[1, 2, 3, 4, 5, 'f']]
def test_excel_write(self):
try:
dumper = ExcelDumper()
dumper.write_matrix_to_sheet(headings=['col1','col2','col3','col4','col5','col6'],matrix=self.matrix)
except Exception, e:
self.fail("No exceptions should be raised")
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment