Commits (3)
This source diff could not be displayed because it is too large. You can view the blob instead.
#!/usr/bin/env python3
Handy functions and classes used to ease convert job
import json
import re
import xlrd
def ends_with(text, subtext):
""" Tests if given text ends with given subtext """
subtext_len = len(subtext)
if subtext_len > len(text):
return False
return text[-subtext_len:] == subtext
def write_json_file(file_path, data):
""" Writes data the json way to file_path """
with open(file_path, 'w', encoding='utf-8') as json_fd:
json.dump(data, json_fd, ensure_ascii=False, indent=2, sort_keys=True)
class XLReader:
""" Easy access to Excel sheet values """
CELL_RE = re.compile('^([A-Z])([0-9]+)$')
def __init__(self, excel_filepath, sheet_name_or_id):
""" XLReader constructor """
book = xlrd.open_workbook(excel_filepath)
if isinstance(sheet_name_or_id, int):
self.sheet = book.sheet_by_index(sheet_name_or_id)
self.sheet = book.sheet_by_name(sheet_name_or_id)
assert self.sheet, "Sheet [{}] not found".format(sheet_name_or_id)
def get_coldata(self, start, end):
""" Creates an iterator on column data """
start_cell = XLReader.code_to_cell_tuple(start)
end_cell = XLReader.code_to_cell_tuple(end)
for row in range(start_cell[0], end_cell[0] + 1):
yield self.sheet.cell_value(row, start_cell[1])
def get_col_values(self, col_id, fromrow=0):
""" Gets cell values in a given column from given row (inclusive) """
return self.sheet.col_values(col_id, start_rowx=fromrow)
def get_col_values_from_cellcode(self, cell_code):
""" Extracts and return non empty cell values in column from a given cell_code """
(row, col) = XLReader.code_to_cell_tuple(cell_code)
return self.get_col_values(col, fromrow=row)
def get_cellvalue(self, code):
""" Gets column value from cell code """
cel_coords = XLReader.code_to_cell_tuple(code)
return self.get_cellvalue_from_cell_tuple(cel_coords)
def get_cellvalue_from_cell_tuple(self, coords):
""" Gets column value from (row, col) """
return self.sheet.cell_value(*coords)
def code_to_cell_tuple(cell_name):
""" Converts B9 into (8, 1) """
match = XLReader.CELL_RE.match(cell_name)
assert match, 'Bad cell_name: {}'.format(cell_name)
row = int(match.group(2)) - 1
col = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.find(match.group(1))
return (row, col)
This diff is collapsed.