Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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
value = unicode( self.locale.toString( cell.value,
format = 'f',
precision = precision ) )
elif ctype == xlrd.XL_CELL_DATE:
Returns:
str: Type of cell as text
"""
if cell.ctype == TYPE_BLANK:
return 'blank'
if cell.ctype == TYPE_BOOLEAN:
return 'boolean'
if cell.ctype == TYPE_DATE:
return 'date'
if cell.ctype == TYPE_EMPTY:
return 'empty'
if cell.ctype == TYPE_ERROR:
return 'error'
if cell.ctype == TYPE_NUMBER:
return 'number'
if cell.ctype == TYPE_TEXT:
return 'text'
cell.value, style)
return
if rdcoords2d in self.merged_cell_already_set:
# The cell is in a group of merged cells.
# It has been handled by the write_merge() call above.
# We avoid writing a record again because:
# (1) It's a waste of CPU time and disk space.
# (2) xlwt does not (as at 2007-01-12) ensure that only
# the last record is written to the file.
# (3) If you write a data record for a cell
# followed by a blank record for the same cell,
# Excel will display a blank but OOo Calc and
# Gnumeric will display the data :-(
return
wtrow = self.wtsheet.row(wtrowx)
if cty == xlrd.XL_CELL_TEXT:
wtrow.set_cell_text(wtcolx, cell.value, style)
elif cty == xlrd.XL_CELL_NUMBER or cty == xlrd.XL_CELL_DATE:
wtrow.set_cell_number(wtcolx, cell.value, style)
elif cty == xlrd.XL_CELL_BLANK:
wtrow.set_cell_blank(wtcolx, style)
elif cty == xlrd.XL_CELL_BOOLEAN:
wtrow.set_cell_boolean(wtcolx, cell.value, style)
elif cty == xlrd.XL_CELL_ERROR:
wtrow.set_cell_error(wtcolx, cell.value, style)
else:
raise Exception(
"Unknown xlrd cell type %r with value %r at (sheet=%r,rowx=%r,colx=%r)" \
% (cty, cell.value, self.rdsheet.name, rdrowx, rdcolx)
)
def cell_string(sheet, row, col):
cell = sheet.cell(row, col)
if cell.ctype != xlrd.XL_CELL_TEXT:
return None
return cell.value.strip()
def __init__(self, text):
self.value = text
self.ctype = xlrd.XL_CELL_TEXT
import xlrd
import xlwt
rbook = xlrd.open_workbook('cfg_item.xlsx')
rsheet = rbook.sheet_by_index(0)
rcell = rsheet.cell(1, 1)
rrow = rsheet.row(1)
rrow_value = rsheet.row_values(1)
print(rcell)
print(rrow)
print(rrow_value)
ncols = rsheet.ncols
rsheet.put_cell(0, ncols, xlrd.XL_CELL_TEXT, '总数:', None)
t = 0
for row in range(1, rsheet.nrows):
t += rsheet.cell(row, 0).value
# 添加单元格
print(t)
rsheet.put_cell(1, ncols, xlrd.XL_CELL_NUMBER, t, None)
wbook = xlwt.Workbook()
wbook.add_sheet(rsheet.name)
book = xlrd.open_workbook(file_contents=contents)
except xlrd.XLRDError as e:
return None, str(e)
except UnicodeDecodeError:
return None, 'The encoding of the file is unknown.'
if book.nsheets == 0:
return None, 'The uploaded file contains no sheets.'
sheet = book.sheet_by_index(0)
table = []
for row in xrange(sheet.nrows):
table_row = []
for col in xrange(sheet.ncols):
value = None
cell_value = sheet.cell_value(row, col)
cell_type = sheet.cell_type(row, col)
if cell_type == xlrd.XL_CELL_TEXT:
value = cell_value
elif cell_type == xlrd.XL_CELL_NUMBER:
value = str(int(cell_value))
elif cell_type == xlrd.XL_CELL_BOOLEAN:
value = 'true' if cell_value else 'false'
elif cell_type == xlrd.XL_CELL_DATE:
# TODO(ryok): support date type.
pass
table_row.append(value)
table.append(table_row)
csv_output = StringIO.StringIO()
csv_writer = csv.writer(csv_output)
csv_writer.writerows(table)
return csv_output.getvalue(), None
elif ctype == xlrd.XL_CELL_BOOLEAN:
return str(value).upper()
elif ctype == xlrd.XL_CELL_NUMBER:
if value.is_integer():
value = int(value)
return str(value)
elif ctype == xlrd.XL_CELL_DATE:
value = xlrd.xldate_as_tuple(value, datemode)
if value[3:] == (0, 0, 0):
return datetime.date(*value[:3]).isoformat()
else:
return datetime.datetime(*value).isoformat()
elif ctype in (xlrd.XL_CELL_TEXT, xlrd.XL_CELL_EMPTY, xlrd.XL_CELL_BLANK):
return value.encode('utf-8')
raise ValueError(repr(cell), 'unknown cell type')
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:
raise ValueError('Unknown cell type') # error in xlrd
return ret
def cells_all_junk(cells, is_rubbish=None):
"""\
Return True if all cells in the sequence are junk.
What qualifies as junk:
-- empty cell
-- blank cell
-- zero-length text
-- text is all whitespace
-- number cell and is 0.0
-- text cell and is_rubbish(cell.value) returns True.
"""
for cell in cells:
if cell.ctype in null_cell_types:
continue
if cell.ctype == XL_CELL_TEXT:
if not cell.value:
continue
if cell.value.isspace():
continue
if cell.ctype == XL_CELL_NUMBER:
if not cell.value:
continue
if is_rubbish is not None and is_rubbish(cell):
continue
return False
return True