Highlight

Showing posts with label Excel. Show all posts
Showing posts with label Excel. Show all posts

2013-03-05

Digits to Excel column letters

A little tricky, so i'll note it here:

>>> def getLetters(n):
...     o = ""
...     while 1:
...             n, m = divmod(n-1, 26)
...             o = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[m] + o
...             if n < 1: break
...     return o
...
>>> getLetters(1)
'A'
>>> getLetters(25)
'Y'
>>> getLetters(26)
'Z'
>>> getLetters(27)
'AA'

And i might as well include my old getCol function:

def getCol(s):
 z = 0
 for i in range(1, len(s) + 1):
  c = s[-i]
  z += ("ABCDEFGHIJKLMNOPQRSTUVWXYZ".find(c) + 1) * 26**(i - 1)
 return z

2012-06-28

Fixing Python 2.6+ to run Python 3 code:

# -*- coding: utf-8 -*-
from __future__ import print_function
__doc__ = """XLS2DB by Cees Timmerman"""
changelog = """
2012-06-28 v1.0
"""
import glob, locale, os, re, sys, time
#from pyXLSX.xlsx import workbook  # no MergedCells support and fails at Unicode.
from win32com.client import Dispatch  # PyWin32 or ActivePython required. Excel, too.
#from win32com.client.gencache import EnsureDispatch as Dispatch  # Also makes constants available.
#import Image  # PIL to resize images.
import pymysql   # Note: Python 3 doesn't support old db protocol.

print(__doc__)
print(changelog.split("\n")[-2])
print()

if sys.version[:2] == '2.':
 #print("Python 2 sucks at Unicode; use Python 3 to run this.")
 #sys.exit(2)

 # Fix Python 2. We should be running in Python 3, though.
 original_print = print
 def print(*args, **kwargs):
  #original_print("args: " + str(args))
  #original_print("kwargs: " + str(kwargs))
  new_args = []
  for arg in args:
   try:
    new_args.append(arg.encode('ascii', errors='xmlcharrefreplace'))
   except:
    new_args.append(arg)
  original_print(*new_args, **kwargs)
 
 try:
  input = raw_input
  str = unicode
 except: pass