Sunday, January 4, 2009

[python-win32] Problem about formatting a cell in Excel

[python-win32] Problem about formatting a cell in Excel: "FormatDict = { 'currency' : '$#,##0.00;[Red]-$#,##0.00', 'date' : 'mm/dd/yy', 'percent' : '0.0%', 'text' : '@' } def formatrange(format, row1, col1, row2, col2): range = sheet.Range(sheet.Cells(row1, col1), sheet.Cells(row2, col2) ) range.NumberFormat = FormatDict['text'] # format first four columns / 20 rows as text formatrange('text', 1, 1, 20, 4) # format next column as currency formatrange('currency', 1, 5, 20, 5) Here, FormatDict is a global variable. When I need to format a range of cells, I simply get the a reference to the range using normal methods, and set the NumberFormat property of that range to one of the values held in the FormatDict. The dict just lets me use a human-readable description of the format instead of a potentially-obscure series of punctuation characters."

No comments: