Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""Format a value with the pattern set for column.
If no format pattern is set for column, value is returned
unchanged.
Args:
col (int): Column number
cell (xlrd.sheet.Cell): Excel cell
Returns:
str: Formatted value
"""
pat = self.get(col)
log('col=%r, pat=%r, cell=%r', col, pat, cell)
if not pat or cell.ctype in (TYPE_BOOLEAN, TYPE_ERROR, TYPE_EMPTY):
return self._format_default(cell)
if cell.ctype == TYPE_DATE:
dt = xldate_as_datetime(cell.value, self.datemode)
formatted = dt.strftime(pat)
else:
try:
formatted = pat % cell.value
except Exception: # Try new-style formatting
try:
formatted = pat.format(cell.value)
except Exception:
formatted = cell.value
# log('pat=%r, %r --> %r', pat, cell.value, formatted)
.. warning::
The formatting applied by this method is severely limited; for
instance, you won't probably get the exact WYSIWYG between the Excel
spreadsheet and :class:`XLSGrid`.
"""
ctype, value = cell.ctype, cell.value
self.value = "%s"%value
isDate = False
if ctype == xlrd.XL_CELL_DATE:
value = xlrd.xldate_as_tuple(value, datemode)
isDate = True
elif ctype in [xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK]:
return
elif ctype == xlrd.XL_CELL_TEXT:
self.value = "%s"%value
return
elif ctype == xlrd.XL_CELL_ERROR:
value = xlrd.error_text_from_code(ctype)
self.value = "%s"%value
return
self.FormatString(value, isDate, format.format_str)
def __is_header_row(self, row_idx):
try:
from excelrd import XL_CELL_EMPTY
except ImportError:
from xlrd import XL_CELL_EMPTY
return XL_CELL_EMPTY not in self._worksheet.row_types(
row_idx, self._start_col_idx, self._end_col_idx + 1
)
def import_xls(self):
"""Validate and read xls file to update quotation
"""
context = dict(self._context)
fdata = self.xls_file
fname = '/tmp/%s' % (self.xls_name)
f = open(fname, 'w')
f.write(base64.b64decode(fdata))
f.close()
doc = xlrd.open_workbook(fname)
sheet = doc.sheet_by_index(0)
purchase = self.env['purchase.order'].browse(
context['active_ids'])[0]
# validate template format
if sheet.cell_type(2, 5) not in \
(xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK) and \
sheet.cell_value(2, 5) != purchase.name:
raise UserError(' '.join([
_('Is not a valid template for Quotation'),
str(purchase.name)]))
eof = self.get_xls_eof(sheet)
# First col header on Qweb report: template.xml
col_start = "External ID"
can_start = False
done_ids = []
new_products = []
for row in range(eof):
if not can_start:
if col_start == sheet.cell_value(row, 0):
can_start = True
continue
# External ID
True
"""
date_format = kwargs.get('date_format', '%Y-%m-%d')
dt_format = kwargs.get('dt_format', '%Y-%m-%d %H:%M:%S')
time_format = kwargs.get('time_format', '%H:%M:%S')
def time_func(value):
"""Converts an excel time into python time"""
args = xlrd.xldate_as_tuple(value, mode)[3:]
return time(*args).strftime(time_format)
switch = {
XL_CELL_DATE: lambda v: xl2dt(v, mode).strftime(date_format),
'datetime': lambda v: xl2dt(v, mode).strftime(dt_format),
'time': time_func,
XL_CELL_EMPTY: lambda v: '',
XL_CELL_NUMBER: str,
XL_CELL_BOOLEAN: lambda v: str(bool(v)),
XL_CELL_ERROR: lambda v: xlrd.error_text_from_code[v],
}
for i in range(sheet.nrows):
types = sheet.row_types(i)[first_col:]
values = sheet.row_values(i)[first_col:]
for _type, value in zip(types, values):
if _type == XL_CELL_DATE and value < 1:
_type = 'time'
elif _type == XL_CELL_DATE and not value.is_integer:
_type = 'datetime'
yield (i, switch.get(_type, lambda v: v)(value))
def convert(self):
if self.wSheet:
num_rows = self.wSheet.nrows - 1
num_cells = self.wSheet.ncols - 1
emptyType = set([xlrd.XL_CELL_BLANK, xlrd.XL_CELL_EMPTY]);
curr_row = -1
while curr_row < num_rows:
curr_row += 1
liste = []
row = self.wSheet.row(curr_row)
if not all(x in emptyType for x in row):
curr_cell = -1
while curr_cell < num_cells:
curr_cell += 1
cell_type = self.wSheet.cell_type(curr_row, curr_cell)
cell_value = self.wSheet.cell_value(curr_row, curr_cell)
if cell_type == xlrd.XL_CELL_BOOLEAN:
try:
liste.append(str(int(cell_value)))
except (ValueError, OverflowError):
# A list of Ref3D objects
for i in range(len(value)):
ref3d = value[i]
print("Range %d: %s ==> %s"% (i, REPR(ref3d.coords), REPR(xlrd.rangename3d(book, ref3d))), file=f)
if not show_contents:
continue
datemode = book.datemode
for shx in range(ref3d.shtxlo, ref3d.shtxhi):
sh = book.sheet_by_index(shx)
print(" Sheet #%d (%s)" % (shx, sh.name), file=f)
rowlim = min(ref3d.rowxhi, sh.nrows)
collim = min(ref3d.colxhi, sh.ncols)
for rowx in range(ref3d.rowxlo, rowlim):
for colx in range(ref3d.colxlo, collim):
cty = sh.cell_type(rowx, colx)
if cty == xlrd.XL_CELL_EMPTY and show_contents == 1:
continue
cval = sh.cell_value(rowx, colx)
sval = showable_cell_value(cty, cval, datemode)
print(" (%3d,%3d) %-5s: %s"
% (rowx, colx, xlrd.cellname(rowx, colx), REPR(sval)), file=f)
def convert_xl_row(xlrdbook, xlrdsheetname, rownum):
'''Converts an xlrd excel worksheet row into a standard python format.
Empty or blank cells -> None
Number or text -> float or string
Boolean -> True or False
Date -> date string as rendered by datetime.datetime
Raises ValueError if a cell has an error.'''
xlrdsheet = xlrdbook.sheet_by_name(xlrdsheetname)
ret = []
for i, cell in enumerate(xlrdsheet.row(rownum)):
if (cell.ctype == _xlrd.XL_CELL_EMPTY or
cell.ctype == _xlrd.XL_CELL_BLANK):
ret.append(None)
elif (cell.ctype == _xlrd.XL_CELL_NUMBER or
cell.ctype == _xlrd.XL_CELL_TEXT):
ret.append(cell.value)
elif cell.ctype == _xlrd.XL_CELL_BOOLEAN:
ret.append(bool(cell.value))
elif cell.ctype == _xlrd.XL_CELL_DATE:
dt = _xlrd.xldate_as_tuple(cell.value, xlrdbook.datemode)
d = str(_datetime.datetime(*dt))
ret.append(d)
elif cell.ctype == _xlrd.XL_CELL_ERROR:
raise ValueError(
' '.join(['Cell', _xlrd.cellname(rownum, i), 'in sheet',
xlrdsheet.name, 'has an error']))
else:
def next( self ):
import xlrd
if self.current_row < self.rows:
vector = []
for column in range( self.sheet.ncols ):
cell = self.sheet.cell( self.current_row, column )
ctype = cell.ctype
value = ''
if ctype in( xlrd.XL_CELL_EMPTY,
xlrd.XL_CELL_ERROR,
xlrd.XL_CELL_BLANK ):
pass
elif ctype == xlrd.XL_CELL_TEXT:
value = unicode( cell.value )
elif ctype == xlrd.XL_CELL_NUMBER:
format_string = self.get_format_string( cell.xf_index )
# try to display the number with the same precision as
# it was displayed in excel
precision = max( 0, format_string.count('0') - 1 )
# see the arguments format documentation of QString
# format can be eiter 'f' or 'e', where 'e' is scientific
# so maybe the format string should be parsed further to
# see if it specifies scientific notation. scientific
# notation is not used because it loses precision when
# converting to a string
# A list of Ref3D objects
for i in xrange(len(value)):
ref3d = value[i]
print >> f, "Range %d: %r ==> %s"% (i, ref3d.coords, xlrd.rangename3d(book, ref3d))
if not show_contents:
continue
datemode = book.datemode
for shx in xrange(ref3d.shtxlo, ref3d.shtxhi):
sh = book.sheet_by_index(shx)
print >> f, " Sheet #%d (%s)" % (shx, sh.name)
rowlim = min(ref3d.rowxhi, sh.nrows)
collim = min(ref3d.colxhi, sh.ncols)
for rowx in xrange(ref3d.rowxlo, rowlim):
for colx in xrange(ref3d.colxlo, collim):
cty = sh.cell_type(rowx, colx)
if cty == xlrd.XL_CELL_EMPTY and show_contents == 1:
continue
cval = sh.cell_value(rowx, colx)
sval = showable_cell_value(cty, cval, datemode)
print >> f, " (%3d,%3d) %-5s: %r" \
% (rowx, colx, xlrd.cellname(rowx, colx), sval)