<s> from __future__ import division , print_function , absolute_import <EOL> import locale <EOL> from petl . compat import izip_longest , next , xrange <EOL> from petl . util . base import Table <EOL> def fromxls ( filename , sheet = None , use_view = True ) : <EOL> """<STR_LIT>""" <EOL> return XLSView ( filename , sheet = sheet , use_view = use_view ) <EOL> class XLSView ( Table ) : <EOL> def __init__ ( self , filename , sheet = None , use_view = True ) : <EOL> self . filename = filename <EOL> self . sheet = sheet <EOL> self . use_view = use_view <EOL> def __iter__ ( self ) : <EOL> if self . use_view : <EOL> from petl . io import xlutils_view <EOL> wb = xlutils_view . View ( self . filename ) <EOL> if self . sheet is None : <EOL> ws = wb [ <NUM_LIT:0> ] <EOL> else : <EOL> ws = wb [ self . sheet ] <EOL> for row in ws : <EOL> yield tuple ( row ) <EOL> else : <EOL> import xlrd <EOL> with xlrd . open_workbook ( filename = self . filename , on_demand = True ) as wb : <EOL> if self . sheet is None : <EOL> ws = wb . sheet_by_index ( <NUM_LIT:0> ) <EOL> elif isinstance ( self . sheet , int ) : <EOL> ws = wb . sheet_by_index ( self . sheet ) <EOL> else : <EOL> ws = wb . sheet_by_name ( str ( self . sheet ) ) <EOL> for rownum in xrange ( ws . nrows ) : <EOL> yield tuple ( ws . row_values ( rownum ) ) <EOL> def toxls ( tbl , filename , sheet , encoding = None , style_compression = <NUM_LIT:0> , <EOL> styles = None ) : <EOL> """<STR_LIT>""" <EOL> import xlwt <EOL> if encoding is None : <EOL> encoding = locale . getpreferredencoding ( ) <EOL> wb = xlwt . Workbook ( encoding = encoding , style_compression = style_compression ) <EOL> ws = wb . add_sheet ( sheet ) <EOL> if styles is None : <EOL> for r , row in enumerate ( tbl ) : <EOL> for c , v in enumerate ( row ) : <EOL> ws . write ( r , c , label = v ) <EOL> else : <EOL> it = iter ( tbl ) <EOL> hdr = next ( it ) <EOL> flds = list ( map ( str , hdr ) ) <EOL> for c , f in enumerate ( flds ) : <EOL> ws . write ( <NUM_LIT:0> , c , label = f ) <EOL> if f not in styles or styles [ f ] is None : <EOL> styles [ f ] = xlwt . Style . default_style <EOL> styles = [ styles [ f ] for f in flds ] <EOL> for r , row in enumerate ( it ) : <EOL> for c , ( v , style ) in enumerate ( izip_longest ( row , styles , <EOL> fillvalue = None ) ) : <EOL> ws . write ( r + <NUM_LIT:1> , c , label = v , style = style ) <EOL> wb . save ( filename ) <EOL> Table . toxls = toxls </s>
