Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
psyco.full()
PSYCO = 0
try:
t0 = time.time()
bk = xlrd.open_workbook(fname,
verbosity=options.verbosity, logfile=logfile,
use_mmap=mmap_arg,
encoding_override=options.encoding,
formatting_info=fmt_opt,
on_demand=options.on_demand,
ragged_rows=options.ragged_rows,
)
t1 = time.time()
if not options.suppress_timing:
print("Open took %.2f seconds" % (t1-t0,))
except xlrd.XLRDError as e:
print("*** Open failed: %s: %s" % (type(e).__name__, e))
continue
except KeyboardInterrupt:
print("*** KeyboardInterrupt ***")
traceback.print_exc(file=sys.stdout)
sys.exit(1)
except BaseException as e:
print("*** Open failed: %s: %s" % (type(e).__name__, e))
traceback.print_exc(file=sys.stdout)
continue
t0 = time.time()
if cmd == 'hdr':
bk_header(bk)
elif cmd == 'ov': # OverView
show(bk, 0)
elif cmd == 'show': # all rows
for row in rows:
name = row[col_indices[column_names[0]]].value.replace("'", r'\'')
code = row[col_indices[column_names[1]]].value
suffix = row[col_indices[column_names[2]]].value.replace("'", r'\'')
key = unit_key_from_name(name)
if key in seen:
continue
seen.add(key)
# Split on ' or ' to support the units like '% or pct'
for suffix in suffix.split(' or '):
yield "%s = UnitDescriptor('%s', '%s', '''%s''')\n" % (
key, name, code, suffix)
yield "ALL_UNITS.append(%s)\n" % key
except xlrd.XLRDError:
sys.stdout.write('Unable to process the .xls file.')
# First, we'll try to parse the file as if it is xml.
try:
excelHandler = ExcelHandler()
parse(filepath, excelHandler)
# Create the dataframe from the parsed data
df = pd.DataFrame(excelHandler.tables[0][2:],
columns=excelHandler.tables[0][1])
# Convert the "Generation [MWh]"-column to numeric
df['Generation [MWh]'] = pd.to_numeric(df['Generation [MWh]'])
except:
# In the case of an exception, treat the file as excel.
try:
df = pd.read_excel(filepath, header=1)
except xlrd.XLRDError:
df = pd.DataFrame()
return df
def convert_xsl_to_csv(contents):
"""Converts data in xsl (or xslx) format to CSV."""
try:
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:
def _load_workbook(self):
try:
self.workbook = pd.ExcelFile(self.path_to_excel_file)
except XLRDError as ex:
logger.error("invalid format of excel file '%s' (%s)" % (self.path_to_excel_file, ex), exc_info=True)
raise InvalidExcelFileFormat("invalid file format") from ex
except Exception:
logger.fatal("unable to read workbook at '%s'" % self.path_to_excel_file, exc_info=True)
raise
if debug and len(all_files) < len(xlsxfiles):
# Print msg
pass
for f in all_files:
try:
xlsform = Xlsform(f, suffix=suffix, pma=pma)
xlsforms.append(xlsform)
if check_versioning:
xlsform.version_consistency()
except XlsformError as e:
error.append(str(e))
except IOError:
msg = u'"%s" does not exist.'
msg %= f
error.append(msg)
except XLRDError:
msg = u'"%s" does not appear to be a well-formed MS-Excel file.'
msg %= f
error.append(msg)
except Exception as e:
traceback.print_exc()
error.append(repr(e))
if preexisting:
pass
# overwrite_errors = get_overwrite_errors(xlsforms)
# error.extend(overwrite_errors)
if pma:
pass
# try:
# check_hq_fq_headers(xlsforms)
# check_hq_fq_match(xlsforms)
# except XlsformError as e:
def check_xls(self):
""" Check if the contents is a XLS file """
try:
wb = xlrd.open_workbook(self.file)
sh = wb.sheet_by_name('Sheet1')
except XLRDError:
pass
else:
if is_yes("This seems like a XLS file. Do you wish to transform it to CSV first?"):
with self.rework() as target:
for row in range(sh.nrows):
target.writerow(sh.row_values(row))
return True
def read_sheet_by_name(self, sheet_name):
self._native_book = self._get_book(on_demand=True)
try:
sheet = self._native_book.sheet_by_name(sheet_name)
except xlrd.XLRDError:
raise ValueError("%s cannot be found" % sheet_name)
return self.read_sheet(sheet)
def workbook(self):
try:
wb = xlrd.open_workbook(self.filename, logfile=open(os.devnull, mode="w"))
except xlrd.XLRDError as exp:
logging.error(
f"Cannot load workbook ({repr(exp.args[0])}) on {self.relative_filename}"
)
return None
else:
return wb
raise RuntimeError("xls2tree: invalid source %s" % type(source))
# Find the sheet
try:
if isinstance(sheet, (int, long)):
s = wb.sheet_by_index(sheet)
elif isinstance(sheet, basestring):
s = wb.sheet_by_name(sheet)
elif sheet is None:
if DEFAULT_SHEET_NAME in wb.sheet_names():
s = wb.sheet_by_name(DEFAULT_SHEET_NAME)
else:
s = wb.sheet_by_index(0)
else:
raise SyntaxError("xls2tree: invalid sheet %s" % sheet)
except IndexError, xlrd.XLRDError:
s = None
def cell_range(cells, max_cells):
"""
Helper method to calculate a cell range
@param cells: the specified range
@param max_cells: maximum number of cells
"""
if not cells:
cells = (0, max_cells)
elif not isinstance(cells, (tuple, list)):
cells = (0, cells)
elif len(cells) == 1:
cells = (cells[0], max_cells)
else: