xls to txt

Pettersen, Bjorn S BjornPettersen at fairisaac.com
Thu Oct 16 23:37:06 EDT 2003


> From: Gilles Lenfant [mailto:glenfant at NOSPAM.bigfoot.com] 
> 
> > "Enrique" enrique.palomo at xgs-spain.com> a écrit dans le 
> > message de news:
> >
> > mailman.141.1066299641.2192.python-list at python.org...
> > Hello all,
> > I`m searching in www, win32com docs, o'really examples, ... 
> > and i can´t find anything that i can use.
> >
> > i wan`t to make a simple script to pass an excel file to txt file.
> >
> > where can i find the methods to work, or sample code??
> >
> > Thanks
> 
> win32all comes with sample of reading xls sheets as python 
> objects! You can get either the formula or the result.
> Be warned that the returned text is unicode. You should 
> consider working with .csv exports that are easier 
> to play with, bet perhaps it's not an option for you.

see below for xls to tab-delimited conversion.

> Please post here in plain text in the future.

please :-)

> --Gilles

-- bjorn

class FileExistsError(Exception): pass

class ExcelNotInstalled(Exception): pass

if __name__ == "__main__":
    xl = None
    try:
        if len(sys.argv) < 3:
            print 'Usage - ConvertExcelToText InputFile OutputFile'
            sys.exit(20)
        
        from win32com.client import Dispatch
        
        input = sys.argv[1]
        output = sys.argv[2]
        
        try:
            xl = Dispatch("Excel.Application.10")
        except:
            raise ExeclNotInstalled('You must install Excel to use this converter.')
        #xl.Visible = 1
    
        wb = xl.Workbooks.Open(input)
        if os.path.exists(output):
            raise FileExistsError(output + " allready exists, can't overwrite.")
        wb.SaveAs(Filename = output, FileFormat = 0x14)
        wb.Close(SaveChanges=0)
    
        if len(xl.Workbooks) == 0:    
            xl.Quit()
        
    finally:
        if xl is not None:
            xl.Quit()
    





More information about the Python-list mailing list