diff --git a/pyproject.toml b/pyproject.toml index bb1924b..d53668e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,5 +20,6 @@ requires = [ [tool.flit.scripts] xls2changelog = "work_helpers.excel2changelog:cli" +xls2markdown = "work_helpers.excel2markdown:cli" sg_mbp_release = "work_helpers.sg_mbp_release:sg_mbp_release" sg_mbp_new_version = "work_helpers.sg_mbp_release:sg_mbp_new_version" diff --git a/work_helpers/excel2markdown.py b/work_helpers/excel2markdown.py new file mode 100644 index 0000000..9b12e70 --- /dev/null +++ b/work_helpers/excel2markdown.py @@ -0,0 +1,56 @@ + +import click +import pyperclip + +def split_table(text): + rows = [] + for line in text.splitlines(): + values = line.split("\t") + cells = [v.strip() for v in values] + rows.append(cells) + return rows + + +def get_cell_lengths(table): + tmp = { } + + for row in table: + for i, cell in enumerate(row): + if i not in tmp: + tmp[i] = [] + tmp[i].append(len(cell)) + + return {k: max(v) for k, v in tmp.items()} + +def build_table(table, lengths): + text_rows = [_build_row(row, lengths) for row in table] + header, *rest = text_rows + sep_items = [ + "-" * lengths[k] for k in sorted(lengths.keys()) + ] + separator = _build_line(sep_items) + lines = [header, separator] + rest + return "\r\n".join(lines) + +def _build_row(row, lengths): + items = [] + for i, cell in enumerate(row): + length = lengths[i] + items.append(cell.ljust(length)) + return _build_line(items) + +def _build_line(items): + tmp = " | ".join(items) + return f"| {tmp} |" + + + +@click.command() +def cli(): + xls = pyperclip.paste() + table = split_table(xls) + lengths = get_cell_lengths(table) + result = build_table(table, lengths) + print("copied to clipboard") + pyperclip.copy(result) +